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

Easy way to get Local Storage Value to Content Script [Chrome Extension]

我想要一些存储在本地存储中的数据到内容脚本页面。由于它不是直接可用的,我通过 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});
  • Full documentation.

  • My recent answer 关于 Chrome storage API.

  • Overview of localStorage vs chrome.storage.