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

发布于 2024-09-27 08:42:09 字数 234 浏览 3 评论 0原文

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

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

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

I have an options page where the user can define certain options and it saves it in localStorage: options.html

Now, I also have a content script that needs to get the options that were defined in the options.html page, but when I try to access localStorage from the content script, it doesn't return the value from the options page.

How do I make my content script get values from localStorage, from the options page or even the background page?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

岁月苍老的讽刺 2024-10-04 08:42:09

2016 年更新:

Google Chrome 发布了存储 API:https://developer.chrome.com/ docs/extensions/reference/storage/

与其他 Chrome API 一样,它非常易于使用,您可以在 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”

使用本机 localStorage (旧回复从 2011 年起

内容脚本在网页上下文中运行,而不是在扩展页面中运行。因此,如果您从内容脚本访问 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 数组。

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

变得花哨和通用......

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.
});

Update 2016:

Google Chrome released the storage API: https://developer.chrome.com/docs/extensions/reference/storage/

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"
    ],

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

Using native localStorage (old reply from 2011)

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.

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.
});

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.

To be fancy and generic ...

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.
});
愛上了 2024-10-04 08:42:09

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

  • 存储内容脚本中的信息而不需要
    内容脚本和扩展之间的消息传递;
  • 将数据存储为 JavaScript 对象,而不将其序列化为 JSON(localStorage 仅存储字符串)。

这是一个简单的代码,演示了 chrome.storage 的使用。 Content script 获取访问页面的 url 和时间戳并存储它,popup.js 从存储区域获取它。

content_script.js

(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)
    });
})();

popup.js

(function () {
    chrome.storage.onChanged.addListener(function (changes,areaName) {
        console.log("New item in storage",changes.visitedPages.newValue);
    })
})();

这里的“Changes”是一个包含给定键的旧值和新值的对象。 “AreaName”参数指的是存储区域的名称,可以是“本地”、“同步”或“托管”。

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

ma​​nifest.json

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

Sometimes it may be better to use chrome.storage API. It's better then localStorage because you can:

  • store information from your content script without the need for
    message passing
    between content script and extension;
  • store your data as JavaScript objects without serializing them to JSON (localStorage only stores strings).

Here's a simple code demonstrating the use of chrome.storage. Content script gets the url of visited page and timestamp and stores it, popup.js gets it from storage area.

content_script.js

(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)
    });
})();

popup.js

(function () {
    chrome.storage.onChanged.addListener(function (changes,areaName) {
        console.log("New item in storage",changes.visitedPages.newValue);
    })
})();

"Changes" here is an object that contains old and new value for a given key. "AreaName" argument refers to name of storage area, either 'local', 'sync' or 'managed'.

Remember to declare storage permission in manifest.json.

manifest.json

...
"permissions": [
    "storage"
 ],
...
瑶笙 2024-10-04 08:42:09

[对于清单 v3]

您可以执行从网页返回本地存储项目的脚本。该脚本可以从弹出窗口或后台服​​务工作者执行。

在manifest.json中添加以下行:

"permissions": ["scripting"]


 let [tab] = await chrome.tabs.query({ active: true, currentWindow: true })

 // Execute script in the current tab
  const fromPageLocalStore = await chrome.scripting.executeScript({
    target: { tabId: tabId },
    func: () => {
      return JSON.stringify(localStorage)
    }
  })

  const localStorageItems = JSON.parse(fromPageLocalStore[0].result)

[For manifest v3]

You can execute a script that returns localstorage items from the webpage. This script can be executed from popup or background service worker.

Add this line in manifest.json:

"permissions": ["scripting"]


 let [tab] = await chrome.tabs.query({ active: true, currentWindow: true })

 // Execute script in the current tab
  const fromPageLocalStore = await chrome.scripting.executeScript({
    target: { tabId: tabId },
    func: () => {
      return JSON.stringify(localStorage)
    }
  })

  const localStorageItems = JSON.parse(fromPageLocalStore[0].result)
痴情换悲伤 2024-10-04 08:42:09

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

一个缺点是它是异步的。

https://developer.chrome.com/extensions/storage.html

Another option would be to use the chromestorage API. This allows storage of user data with optional syncing across sessions.

One downside is that it is asynchronous.

https://developer.chrome.com/extensions/storage.html

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文