Chrome扩展程序:在后台存储数据

Thi*_*lem 1 javascript local-storage google-chrome-extension

我希望能够在后台(在我的扩展名上)存储数据,以便我可以在多个域之间访问此数据.

我在做什么:

内容的script.js

function setItem(name, data) {
    chrome.extension.sendMessage({ command: 'setItem', name: name, data: data });
}

function getItem(name) {
    chrome.extension.sendMessage({ command: 'getItem', name: name }, function(response) {
        return response;
    });
}
Run Code Online (Sandbox Code Playgroud)

背景的script.js

Storage.prototype.setObject = function(key, value) {
    this.setItem(key, JSON.stringify(value));
}

Storage.prototype.getObject = function(key) {
    var value = this.getItem(key);
    return value && JSON.parse(value);
}

chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
    switch (request.command) {
        case 'setItem':
            localStorage.setObject(request.name, request.data);
            return;
        case 'getItem':
            sendResponse(localStorage.getObject(request.name));
            return;
    }
});
Run Code Online (Sandbox Code Playgroud)

但是没有成功,因为我无法从getItem的回调中返回.

我确实得到了function(response) { }回调内的数据,我只是无法将其作为getItem的返回值返回.

我该怎么做?

Xan*_*Xan 9

这个2012年的问题提出了最新的答案.好吧..

现在正确的答案是使用chrome.storageAPI.它是一个可用于扩展页面和内容脚本的API,它提供异步存储.它需要"storage"权限,但此权限不会生成警告.

// Setting
chrome.storage.local.set({key: data}, function() {
  if(chrome.runtime.lastError) {
    console.error(
      "Error setting " + key + " to " + JSON.stringify(data) +
      ": " + chrome.runtime.lastError.message
    );
  }
});

// Getting
chrome.storage.local.get("key", function(data) {
  // Do something with data.key
});
Run Code Online (Sandbox Code Playgroud)

另请参阅文档的示例部分.

请注意,在这两种情况下(这种做法,或消息最背景的方法),你不能让一个函数getData返回一个结果,因为调用是异步的.

一些提示和技巧:

  1. 您可以通过将对象或数组作为查询传递来一次设置或获取多个值.您可以通过传递null查询来读取所有值.

  2. 您可以get()通过传递类似的查询,在没有为密钥存储值的情况下为操作提供默认值{key: defaultValue}

  3. 您可以通过事件通知存储的所有更改chrome.storage.onChanged.

  4. chrome.storage.local服从"unlimitedStorage"许可.

  5. chrome.storage.sync如果为扩展程序启用了Chrome同步,则会将该值传播到登录到同一Google帐户的所有个人资料.但是,请记住配额.

  6. 如果您绝对需要同步访问,则可以使用支持的本地缓存伪造它chrome.storage.但是,有一些限制:在同步代码块中,您的缓存不会随着其他页面的更改而更新,您需要异步读取值以填充缓存.


Chr*_*ris 5

Content.js

var someVar = "hey hey!";

chrome.extension.sendRequest({method: "fromContentScript",greeting: someVar}, function(response) {

    console.log(response.data); // response back from BG

    if(response.who == 'bg'){ // checks if the response is from BG
            //Something happened ...
    }

    var responseFromBg = response.data; // the response incase we need to use the message sent back... in this case should be 'hey yourself'


});
Run Code Online (Sandbox Code Playgroud)

Background.js

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
  // From content script.
  if (sender.tab) {
    if (request.method == "fromContentScript"){

        localStorage.setItem("welcome-message",request.greeting); // in this case there will now be a localStorage variable called 'welcome-message' set with the value of 'hey hey!'. This will be viewable in the chrome:extensions page, click on the 'background.html / generated background.html' then view the 'Development Tools' or in Windows hit 'CTRL + SHIFT + I' and look at the 'LocalStorage' tab...

      sendResponse({who: "bg",data: "hey yourself"}); // this is the response sent back, 'who' tells the content page where is responding, so it can do something with the response if needed.
        }else{
      sendResponse({}); // snub them.
        }
  }
});
Run Code Online (Sandbox Code Playgroud)

Manifest.json //只是因为这是一个明显的问题,你有...这里是我的大多数..

{
  "name": "Name here",
  "version": "1",
  "manifest_version": 2,
  "description": "Enter desc here.",  
    "browser_action": {
    "default_icon": "img/icon16.png",
    "default_popup": "popup.html"
  },    
    "background": {
    "scripts": ["background.js"]
  },
  "permissions": [
    "tabs", "*://*/*"
  ],
    "icons": { "16": "img/icon16.png",
           "48": "img/icon48.png",
          "128": "img/icon128.png" },
  "content_scripts": [
    {
      "matches": ["*://*/*"],
      "js": ["js/jquery-1.7.2.min.js","content_script.js"],
      "run_at": "document_end"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

本来可以用你的例子,但我很匆忙.我试图尽可能仔细地解释所有的变种 - 对不起:(