繁体   English   中英

获取本地存储值到内容脚本[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});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM