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

use*_*214 148 local-storage google-chrome-extension content-script

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

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

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

Moh*_*our 220

2016年更新:

Google Chrome发布了存储API:http://developer.chrome.com/extensions/storage.html

与其他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);
    });
Run Code Online (Sandbox Code Playgroud)

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

    "permissions": [
      "storage"
    ],
Run Code Online (Sandbox Code Playgroud)

有一些方法可以"删除","清除","getBytesInUse",以及一个事件监听器来监听已更改的存储"onChanged"

使用native localStorage(2011年的旧回复)

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

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

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

contentscript.js

chrome.runtime.sendMessage({method: "getStatus"}, function(response) {
  console.log(response.status);
});
Run Code Online (Sandbox Code Playgroud)

background.js

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

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

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

要花哨和通用......

contentscript.js

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

background.js

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

  • 后台页面和选项页面属于同一扩展上下文,因此您不需要内容脚本或消息传递.您可以直接从选项页面调用`localStorage`或从选项页面使用`chrome.extension.getBackgroundPage`. (7认同)
  • 试试看:) (5认同)

Paw*_*ech 43

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

  • 存储来自内容脚本的信息,而无需在内容脚本和扩展之间传递消息 ;
  • 将您的数据存储为JavaScript对象,而不将它们序列化为JSON(localStorage仅存储字符串).

这是一个简单的代码,演示了chrome.storage的使用.内容脚本获取被访问页面和时间戳的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)
    });
})();
Run Code Online (Sandbox Code Playgroud)

popup.js

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

这里的"更改"是一个包含给定键的旧值和新值的对象."AreaName"参数是指存储区域的名称,"本地","同步"或"托管".

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

的manifest.json

...
"permissions": [
    "storage"
 ],
...
Run Code Online (Sandbox Code Playgroud)


Jas*_*son 7

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

一个缺点是它是异步的.

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


Jer*_*yal 6

[对于清单 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)
Run Code Online (Sandbox Code Playgroud)