如何使用 WebExtensions 存储恢复复选框的状态 API

How to restore the state of checkboxes using WebExtensions storage API

我正在构建一个 Firefox 网络扩展,我想为其用户提供一些他们可以 check/uncheck 的选项。复选框的状态通过 WebExtensions 存储保存在本地 API,但我不太确定如何为每个选项恢复保存的状态。

这里是 options.html 文件:

<!DOCTYPE html>

<html>
  <head>
    <meta charset="utf-8">
  </head>

<body>
    <form method="post">
        <fieldset>
                <legend>My favorite veggies</legend>
                        <input type="checkbox" name="eggplant" id="eggplant" />Eggplant<br />
                        <input type="checkbox" name="zucchini" id="zucchini" />Zucchini<br />
                        <input type="checkbox" name="tomatoe" id="tomatoe" />Tomatoe<br />
                        <input type="submit" value="Submit" />
        </fieldset>
    </form>
    <script src="options.js"></script>
</body>

</html>

options.js文件saves/restores复选框的状态如下:

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

function saveOptions(e) {
  // List of search engines to be used
  let eggplant = {
      name: "Eggplant", 
      imageUrl: "https://www.organicfacts.net/wp-content/uploads/2013/06/Eggplant-1020x765.jpg",
      show: form.eggplant.checked
  };
  let zucchini = {
      name: "Zucchini", 
      imageUrl: "https://www.organicfacts.net/wp-content/uploads/zucchini.jpg",
      show: form.zucchini.checked
  };
  let tomatoe = {
      name: "Tomatoe", 
      imageUrl: "https://www.organicfacts.net/wp-content/uploads/2013/05/Organictomato1-1020x765.jpg",
      show: form.tomatoe.checked
  };
  let setting = browser.storage.sync.set({
    eggplant,
    zucchini,
    tomatoe
  });
  setting.then(null,onError);
  e.preventDefault();
}

function restoreOptions() {
  var gettingItem = browser.storage.sync.get({
    'show'
  });
  gettingItem.then((res) => {
    document.getElementById("eggplant").checked = eggplant.show;
    document.getElementById("zucchini").checked = zucchini.show;
    document.getElementById("tomatoe").checked = tomatoe.show;
  });
}

document.addEventListener('DOMContentLoaded', restoreOptions);
document.querySelector("form").addEventListener("submit", saveOptions);

这是 set 操作后您的存储状态:

{
  eggplant: {
    name: "Eggplant", 
    imageUrl: "https://www.organicfacts.net/wp-content/uploads/2013/06/Eggplant-1020x765.jpg",
    show: true
  },
  zucchini: { /* ... */ },
  tomatoe: { /* ... */ }
}

但是,在 restoreOptions 中,您使用键 "show" 查询存储 - 或者更具体地说,使用语法上不正确的对象文字 {"show"}.

即使您将其修复为 "show" 也没有这样的顶级键(这是您唯一允许的查询类型),所以结果为空。

  • 如果要查询整个存储,通过null
  • 如果要查询单个顶级键,请将其作为字符串传递。
  • 如果您想要一组您事先知道的顶级密钥,请传递一个密钥字符串数组。
  • 如果您想在密钥不在存储中时提供默认值,请将对象映射键传递给默认值。

以下是使用默认值组织代码的方法:

const defaults = {
  eggplant: {
    name: "Eggplant", 
    imageUrl: "(redacted for brevity)",
    show: false
  },
  zucchini: {
    name: "Zucchini", 
    imageUrl: "(redacted for brevity)",
    show: false
  },
  tomatoe: {
    name: "Tomatoe", 
    imageUrl: "(redacted for brevity)",
    show: false
  }
};

function saveOptions() {
  let settings = {}
  for (let setting in defaults) {
    settings[setting] = {
      ...defaults[setting],       // spread the default values
      show: form[setting].checked // override show with real data
    }
  } 
  browser.storage.sync.set(settings).then(null, onError);
}

function restoreOptions() {
  browser.storage.sync.get(defaults).then(
    (data) => {
      document.getElementById("eggplant").checked = data.eggplant.show;
      document.getElementById("zucchini").checked = data.zucchini.show;
      document.getElementById("tomatoe").checked = data.tomatoe.show;
    }
  );
}

注意:不要使用 submitpreventDefault,只需使用 type="button" 输入和 click.

小编辑: 对象传播 (...defaults[setting]) 仍处于实验阶段(尽管最近 Chrome/FF 支持),更多 ES6-compliant code 会是

for (let setting in defaults) {
  // shallow copy default settings
  settings[setting] = Object.assign({}, defaults[setting]);
  // override show property
  settings[setting].show = form[setting].checked;
}

不那么简洁,更兼容一些。