Chrome消息从后台到内容脚本再到后台

chrome messaging from background to content script to background again

本文关键字:后台 脚本 消息 Chrome      更新时间:2023-09-26

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

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

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

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

内容脚本

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的值或您想要的任何名称