且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Chrome 扩展:在内容脚本中访问 localStorage

更新时间:2023-12-05 08:55:52

2016 年更新:

Google Chrome 发布存储 API:https://developer.chrome.com/文档/扩展/参考/存储/

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

It is pretty easy to use like the other Chrome APIs and you can use it from any page context within 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);
    });

要使用它,请确保在清单中定义它:

To use it, make sure you define it in the manifest:

    "permissions": [
      "storage"
    ],

有remove"、clear"、getBytesInUse"的方法,还有一个事件监听器来监听改变的存储onChanged"

There are methods to "remove", "clear", "getBytesInUse", and an event listener to listen for changed storage "onChanged"

内容脚本在网页上下文中运行,而不是在扩展页面中运行.因此,如果您从 contentscript 访问 localStorage,它将是来自该网页的存储,而不是扩展页面存储.

Content scripts run in the context of webpages, not extension pages. Therefore, if you're accessing localStorage from your contentscript, it will be the storage from that webpage, not the extension page storage.

现在,为了让您的内容脚本读取您的扩展存储(您从选项页面设置它们的位置),您需要使用扩展 消息传递.

Now, to let your content script to read your extension storage (where you set them from your options page), you need to use extension message passing.

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

The first thing you do is tell your content script to send a request to your extension to fetch some data, and that data can be your extension localStorage:

contentscript.js

chrome.runtime.sendMessage({method: "getStatus"}, function(response) {
  console.log(response.status);
});

background.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.method == "getStatus")
      sendResponse({status: localStorage['status']});
    else
      sendResponse({}); // snub them.
});

您可以围绕它执行 API 以将通用 localStorage 数据获取到您的内容脚本中,或者获取整个 localStorage 数组.

You can do an API around that to get generic localStorage data to your content script, or perhaps, get the whole localStorage array.

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

I hope that helped solve your problem.

要花哨和通用...

contentscript.js

chrome.runtime.sendMessage({method: "getLocalStorage", key: "status"}, function(response) {
  console.log(response.data);
});

background.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.method == "getLocalStorage")
      sendResponse({data: localStorage[request.key]});
    else
      sendResponse({}); // snub them.
});