为内容脚本[Chrome扩展]获取本地存储价值的简单方法



我希望一些数据存储在本地存储中,以内容脚本页面。由于它不直接可用,我通过chrome.runtime.sendMessage完成了它。但我有几个值,看起来是这样的。

var username, apikey, openexchange, currency, locale;
chrome.runtime.sendMessage({method: "getLocalStorage", key: "username"}, function(response) {
  username = response.data;
});
chrome.runtime.sendMessage({method: "getLocalStorage", key: "apikey"}, function(response) {
  apikey = response.data;
});
chrome.runtime.sendMessage({method: "getLocalStorage", key: "openexchange"}, function(response) {
  openexchange = response.data;
});
chrome.runtime.sendMessage({method: "getLocalStorage", key: "currency"}, function(response) {
  currency = response.data;
});
chrome.runtime.sendMessage({method: "getLocalStorage", key: "locale"}, function(response) {
  locale = response.data;
});

当值增加时,这个列表会更进一步,相反,有没有其他方法可以将所有值包装在一个函数中?

如有任何帮助,我们将不胜感激。

我将首先回答您的直接问题(出于教育目的),然后提供一种更好的方法(根本不使用localStorage)。


您是编写响应getLocalStorage方法的消息侦听器的人。因此,您可以通过每个请求发送一个以上的值来使其更加通用。

示例:

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
  switch(message.method) {
    // ...
    case "getLocalStorage":
      if(message.key) { // Single key provided
        sendResponse({data: localStorage[message.key]});
      }
      else if(message.keys) { // An array of keys requested
        var data = {};
        message.keys.forEach(function(key) {data[key] = localStorage[key];})
        sendResponse({data: data});
      }
      break;
    // ...
  }
});

所以现在你可以做:

chrome.runtime.sendMessage(
  {method: "getLocalStorage", keys: ["username", "apikey"]},
  function(response) {
    username = response.data.username;
    apikey = response.data.apikey;
  }
);

也就是说,你正在重新发明轮子。Chrome已经有了一个存储API(称为,令人惊讶的是chrome.storage),它正好解决了这种情况:扩展页面和内容脚本都可以使用某种持久存储。

添加"storage"权限后,可以执行以下操作:

chrome.storage.local.get(key, function(data) {
  // Use data[key]
});
chrome.storage.local.get([key1, key2], function(data) {
  // Use data[key1], data[key2]
});
chrome.storage.local.get({key1: default1, key2: default2}, function(data) {
  // Use data[key1], data[key2], and defaults will be used if not yet in storage
});
chrome.storage.local.set({key1: value1, key2: value2});
  • 完整的文档。

  • 我最近关于Chrome storage API的回答。

  • localStoragechrome.storage概述。

最新更新