保存和恢复 webextensions 选项页面

Save and restore webextensions options page

我是编程新手,我正在为 Firefox 构建一个简单的附加组件,但我使用的是 Web 扩展,我的选项页面有几个复选框

我需要保存这些复选框的值然后恢复它们,感谢示例代码。

function saveOptions(e) {
  e.preventDefault();
  browser.storage.local.set({
    box1: document.querySelector("#box1").checked
  });
}

function restoreOptions() {

 var getting = browser.storage.local.get("box1");

  function setCurrentChoice(result) {
    document.querySelector("#box1").checked = result.box1 || false
  }

  function onError(error) {
    console.log(`Error: ${error}`);
  }

  

  getting.then(setCurrentChoice, onError);

}

document.addEventListener("DOMContentLoaded", restoreOptions);
document.querySelector("form").addEventListener("submit", saveOptions);
<form>
<p><label>Box1<input id="box1" type="checkbox" /></label></p>
<p><label>Box2<input id="box2" type="checkbox" /></label></p>
<p><label>Box3<input id="box3" type="checkbox" /></label></p>
<p><label>Box4<input id="box4" type="checkbox" /></label></p>
<p><label>Box5<input id="box5" type="checkbox" /></label></p>
<p><button type="submit">Save</button></p>
</form>
<script src="options.js"></script>

我从 Firefox 的示例中获得的代码可以保存一个复选框的值,但是我如何保存和恢复不同复选框的所有值?

这是我用的。我的 add-on 也只在选项中使用复选框。在您的示例中,选项由元素 id 标识,因此包含 HTML 将是多余的。我没有保存按钮;无论何时选中或取消选中选项,都会实时记录更改。它主要是从该功能的联机文档中复制的。不过请注意,此变体使用 jQuery。

// see https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Implement_a_settings_page

// if one of the checkboxes is clicked, store the new value of the
// corresponding parameter:
$("input").click(function () {
  var setting = {};
  setting[$(this).attr("id")] = $(this).get(0).checked;
  chrome.storage.local.set(setting);
});

function restoreOptions() {
 // For each checkbox, see if stored value of setting has changed
 $("input").each(function () {
   var id = $(this).attr("id");
   chrome.storage.local.get(id, function (setting) {
     if (Object.keys(setting).length) {
      $("#"+id).get(0).checked = setting[id] ? "checked" : undefined;
     }
     else {
      // This block runs only the first time the settings page is opened.
      init = {};
      init[id] = true;
      chrome.storage.local.set(init);
     }
   });
 });
}

document.addEventListener("DOMContentLoaded", restoreOptions);

正如@Mayken 所说,您的问题可能出在 manifest.json 上。 The example in the documentation 指示将 options.html 放在一个名为 settings 的目录中,并通过将 options_ui.page 设置为 "options.html" 在 manifest.json 中声明这一点。我发现我必须将其拼写为 "settings/options.html" 才能使其正常工作。