Google chrome extension Chrome扩展:在内容脚本中访问本地存储

Google chrome extension Chrome扩展:在内容脚本中访问本地存储,google-chrome-extension,local-storage,content-script,Google Chrome Extension,Local Storage,Content Script,我有一个选项页面,用户可以在其中定义某些选项,并将其保存在本地存储中:options.html 现在,我还有一个内容脚本,需要获取在options.html页面中定义的选项,但是当我尝试从内容脚本访问localStorage时,它不会从选项页面返回值 如何使我的内容脚本从localStorage、选项页面甚至后台页面获取值?Update 2016: Google Chrome发布了存储API: 它与其他ChromeAPI一样易于使用,您可以在Chrome中的任何页面上下文中使用它 //

我有一个选项页面,用户可以在其中定义某些选项,并将其保存在本地存储中:
options.html

现在,我还有一个内容脚本,需要获取在
options.html
页面中定义的选项,但是当我尝试从内容脚本访问localStorage时,它不会从选项页面返回值

如何使我的内容脚本从localStorage、选项页面甚至后台页面获取值?

Update 2016: Google Chrome发布了存储API:

它与其他ChromeAPI一样易于使用,您可以在Chrome中的任何页面上下文中使用它

    // Save it using the Chrome extension storage API.
    chrome.storage.sync.set({'foo': 'hello', 'bar': 'hi'}, function() {
      console.log('Settings saved');
    });

    // Read it using the storage API
    chrome.storage.sync.get(['foo', 'bar'], function(items) {
      message('Settings retrieved', items);
    });
要使用它,请确保在清单中定义它:

    "permissions": [
      "storage"
    ],
有“删除”、“清除”、“getBytesInUse”等方法,还有一个事件侦听器“onChanged”来侦听已更改的存储

使用本地存储(2011年的旧回复) 内容脚本在网页的上下文中运行,而不是在扩展页中运行。因此,如果您要从contentscript访问localStorage,则它将是该网页中的存储,而不是扩展页存储

现在,要让内容脚本读取扩展存储(从选项页设置它们),您需要使用扩展

您要做的第一件事是告诉您的内容脚本向您的扩展发送请求以获取一些数据,这些数据可以是您的扩展localStorage:

contentscript.js

chrome.runtime.sendMessage({method: "getStatus"}, function(response) {
  console.log(response.status);
});
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.method == "getStatus")
      sendResponse({status: localStorage['status']});
    else
      sendResponse({}); // snub them.
});
chrome.runtime.sendMessage({method: "getLocalStorage", key: "status"}, function(response) {
  console.log(response.data);
});
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.method == "getLocalStorage")
      sendResponse({data: localStorage[request.key]});
    else
      sendResponse({}); // snub them.
});
(function () {
    var visited = window.location.href;
    var time = +new Date();
    chrome.storage.sync.set({'visitedPages':{pageUrl:visited,time:time}}, function () {
        console.log("Just visited",visited)
    });
})();
(function () {
    chrome.storage.onChanged.addListener(function (changes,areaName) {
        console.log("New item in storage",changes.visitedPages.newValue);
    })
})();
background.js

chrome.runtime.sendMessage({method: "getStatus"}, function(response) {
  console.log(response.status);
});
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.method == "getStatus")
      sendResponse({status: localStorage['status']});
    else
      sendResponse({}); // snub them.
});
chrome.runtime.sendMessage({method: "getLocalStorage", key: "status"}, function(response) {
  console.log(response.data);
});
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.method == "getLocalStorage")
      sendResponse({data: localStorage[request.key]});
    else
      sendResponse({}); // snub them.
});
(function () {
    var visited = window.location.href;
    var time = +new Date();
    chrome.storage.sync.set({'visitedPages':{pageUrl:visited,time:time}}, function () {
        console.log("Just visited",visited)
    });
})();
(function () {
    chrome.storage.onChanged.addListener(function (changes,areaName) {
        console.log("New item in storage",changes.visitedPages.newValue);
    })
})();
您可以使用API将通用的localStorage数据获取到内容脚本中,或者获取整个localStorage阵列

我希望这有助于解决你的问题

要花哨和普通

contentscript.js

chrome.runtime.sendMessage({method: "getStatus"}, function(response) {
  console.log(response.status);
});
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.method == "getStatus")
      sendResponse({status: localStorage['status']});
    else
      sendResponse({}); // snub them.
});
chrome.runtime.sendMessage({method: "getLocalStorage", key: "status"}, function(response) {
  console.log(response.data);
});
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.method == "getLocalStorage")
      sendResponse({data: localStorage[request.key]});
    else
      sendResponse({}); // snub them.
});
(function () {
    var visited = window.location.href;
    var time = +new Date();
    chrome.storage.sync.set({'visitedPages':{pageUrl:visited,time:time}}, function () {
        console.log("Just visited",visited)
    });
})();
(function () {
    chrome.storage.onChanged.addListener(function (changes,areaName) {
        console.log("New item in storage",changes.visitedPages.newValue);
    })
})();
background.js

chrome.runtime.sendMessage({method: "getStatus"}, function(response) {
  console.log(response.status);
});
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.method == "getStatus")
      sendResponse({status: localStorage['status']});
    else
      sendResponse({}); // snub them.
});
chrome.runtime.sendMessage({method: "getLocalStorage", key: "status"}, function(response) {
  console.log(response.data);
});
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.method == "getLocalStorage")
      sendResponse({data: localStorage[request.key]});
    else
      sendResponse({}); // snub them.
});
(function () {
    var visited = window.location.href;
    var time = +new Date();
    chrome.storage.sync.set({'visitedPages':{pageUrl:visited,time:time}}, function () {
        console.log("Just visited",visited)
    });
})();
(function () {
    chrome.storage.onChanged.addListener(function (changes,areaName) {
        console.log("New item in storage",changes.visitedPages.newValue);
    })
})();

另一种选择是使用chromestorage API。这允许通过可选的跨会话同步来存储用户数据

一个缺点是它是异步的


有时使用API可能更好。它比localStorage更好,因为您可以:

  • 存储内容脚本中的信息,而无需 内容脚本和扩展之间的消息传递
  • 将数据存储为JavaScript对象,无需将其序列化为JSON()
下面是一个演示chrome.storage使用的简单代码。内容脚本获取访问页面的url和时间戳并存储,popup.js从存储区域获取

content\u script.js

chrome.runtime.sendMessage({method: "getStatus"}, function(response) {
  console.log(response.status);
});
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.method == "getStatus")
      sendResponse({status: localStorage['status']});
    else
      sendResponse({}); // snub them.
});
chrome.runtime.sendMessage({method: "getLocalStorage", key: "status"}, function(response) {
  console.log(response.data);
});
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.method == "getLocalStorage")
      sendResponse({data: localStorage[request.key]});
    else
      sendResponse({}); // snub them.
});
(function () {
    var visited = window.location.href;
    var time = +new Date();
    chrome.storage.sync.set({'visitedPages':{pageUrl:visited,time:time}}, function () {
        console.log("Just visited",visited)
    });
})();
(function () {
    chrome.storage.onChanged.addListener(function (changes,areaName) {
        console.log("New item in storage",changes.visitedPages.newValue);
    })
})();
popup.js

chrome.runtime.sendMessage({method: "getStatus"}, function(response) {
  console.log(response.status);
});
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.method == "getStatus")
      sendResponse({status: localStorage['status']});
    else
      sendResponse({}); // snub them.
});
chrome.runtime.sendMessage({method: "getLocalStorage", key: "status"}, function(response) {
  console.log(response.data);
});
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.method == "getLocalStorage")
      sendResponse({data: localStorage[request.key]});
    else
      sendResponse({}); // snub them.
});
(function () {
    var visited = window.location.href;
    var time = +new Date();
    chrome.storage.sync.set({'visitedPages':{pageUrl:visited,time:time}}, function () {
        console.log("Just visited",visited)
    });
})();
(function () {
    chrome.storage.onChanged.addListener(function (changes,areaName) {
        console.log("New item in storage",changes.visitedPages.newValue);
    })
})();
这里的“Changes”是一个包含给定键的新旧值的对象。“AreaName”参数是指存储区域的名称,可以是“本地”、“同步”或“托管”

记住在manifest.json中声明存储权限

manifest.json

...
"permissions": [
    "storage"
 ],
...

Related:Related:Related:显然,请求也可以是{method:'getStorage',key:'status'},侦听器将用相应的数据进行响应。如果我想将localStorage中的所有内容都传输到扩展呢?我可以写
sendResponse({data:localStorage})?我有点困惑。我希望我的选项页面中的数据可以在background.html页面上找到。。所以我从后台页面向contentscript发出请求?contentscript可以发回本地存储数据吗?看到这个->。。我做得对吗?背景页面和选项页面属于相同的扩展上下文,因此您不需要内容脚本或消息。您可以直接从选项页调用
localStorage
,也可以从选项页使用
chrome.extension.getBackgroundPage
。这很奇怪。我在选项页面中设置了几个选项,并在背景页面中基于它们创建上下文菜单。问题是,如果我从选项页面在localStorage中设置了一个变量,它不会立即反映到后台页面(即没有新的contextmenu),除非我禁用并重新启用扩展。您能想到什么原因吗?
onChanged
事件已经在
changes
对象中提供了数据。此外,请特别注意
onChanged
事件的
名称空间
。如果您使用
chrome.storage.local.set
存储某些内容,则会触发
onChanged
事件,但使用
chrome.storage.sync.get
进行读取毫无意义。是的,您是对的,编辑了我的答案。显然,您可以在其他场景中使用chrome.storage.sync.get,但在这里它确实是多余的。作为对您答案第5版的响应:
更改。如果未更改
访问页面
,则访问页面
将是未定义的。用
if(changes.visitedPages){…}
将该行换行以解决此问题。@Jason,处理全部或无事务怎么样?