0

所以我试图将数据从 chrome 背景页面的本地存储发送到内容脚本,然后对数据进行一些操作。之后,我想将其发送回后台页面并更新后台页面的本地存储。这可能吗。我知道如何将数据从后台发送到内容脚本,但是如何从内容脚本发送到后台?

背景.html

var background = chrome.extension.getBackgroundPage();

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse, getBackResponse) {
    if (request.extensionSettings === "storage") {

        // send local storage data {"one": "data", "two": "data"}
        sendResponse({storageString: background.localStorage.extdata});

        // save new data from content script
        localStorage.setItem("extdata", getBackResponse);
    }
 });

脚本.js

chrome.runtime.sendMessage({extensionSettings: "storage"}, function(response) {
  var json = JSON.parse(response.storageString);

  console.log(json);
  // take json object do a few things with data
  // take data and make new json string, and send it background page
  sendBack('{"one": "new data", "two": "more new data"}');
});
4

1 回答 1

3

好吧,在这种情况下,您只想区分发送到后台页面的消息。一种方法是使用这样的简单标识符:

内容脚本

chrome.runtime.sendMessage({method:"getStorage",extensionSettings:"storage"},
function(response) {
  var json = JSON.parse(response.storageString);

  console.log(json);
  // take json object do a few things with data
  // take data and make new json string, and send it background page
  // Let's just say that `sendBack` is now defined to be a var
  // With the info you want to send back
  var sendBack = {"one": "new data", "two": "more new data"};
  chrome.runtime.sendMessage({method:"setStorage", newData:sendBack});
});

有了这个,我们发送一条消息来获取数据,在回调中对其进行操作,然后将其发回。现在来处理它。

背景页面

chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
  if(message.method == "getStorage"){
    if(message.extensionSettings === "storage") {
      // send local storage data {"one": "data", "two": "data"}
      sendResponse({storageString: background.localStorage.extdata});
    }
  }
  else if(message.method == "setStorage"){
    // save new data from content script
    localStorage.setItem("extdata", message.newData);
  }
});

通过这种方式,我们可以处理各种不同类型的消息,只需更改它的值method或您想要命名的任何名称。

于 2013-04-26T05:32:31.807 回答