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

Chrome extension: store data on background

本文关键字:存储 后台 数据 扩展 程序 Chrome      更新时间:2023-09-26

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

我在做什么:

内容脚本.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;
    });
}

后台脚本.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;
    }
});

但是没有成功,因为我无法从getItem的回调内部返回。

我确实在function(response) { }回调中获取了数据,只是无法将其作为getItem的返回返回。

我应该怎么做?

这个

2012年的问题是为了获得最新的答案。那么..

现在正确的答案是使用chrome.storage API。它是一个可供扩展页面和内容脚本访问的 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
});

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

请注意,无论哪种情况(此方法或后台消息传递方法),您都无法创建返回结果的函数getData,因为调用是异步的。

一些提示和技巧:

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

  2. 如果没有为
  3. 键存储值,可以通过传递类似 {key: defaultValue} 的查询,为 get() 操作提供默认值。

  4. 您可以通过chrome.storage.onChanged事件收到对存储的所有更改的通知。

  5. chrome.storage.local服从"unlimitedStorage"许可。

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

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

内容.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'

});

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

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

本来会用你的例子,但我今年很着急。我试图尽可能仔细地解释所有变量 - 对不起:(

background-script.js:

chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
    switch (request.command) {
        case 'setItem':
            localStorage[request.name] = JSON.stringify(request.data));
            return;
        case 'getItem':
            var retValue;
            if (typeof(localStorage[request.name]) === 'string') {
                retValue = JSON.parse(localStorage[request.name]);
            }
            sendResponse(retValue);
            return;
        case 'deleteItem':
            if (typeof localStorage[request.name] !== 'undefined') {
                delete localStorage[request.name];
            }
            return;
    }
});

如果密钥不在 localStorage 中,getItem 将返回 undefined 。与其getItem定义函数,不如使用回调向后台发送消息,然后在调用回调时对该值执行某些操作。不能从函数 getItem 返回值,但可以在调用时在回调中使用该值:

function getItem(name, callback) {
    chrome.extension.sendMessage({command: 'getItem', name: name}, function(response) {
        if (typeof(callback) === "function") {
            callback(response);
        }
    });
}