如何从内容脚本访问后台脚本变量

How to get access to a background script variable from content script

我正在创建一个供自己使用的扩展程序,但我遇到了问题。我想为从 background.jscontent.js 的变量赋值。 background.js 中的变量必须始终存在,尽管刷新了内容页面。如何做到这一点?

manifest.json

{

  "manifest_version": 2,
  "name": "Slownik",
  "version": "1.0",

  "description": "Slownik",

  "background": {
  "scripts": ["background.js"]
  },

  "content_scripts": [
    {
      "matches": ["*://*.sjp.pl/*"],
      "js": ["content.js"]
    }
  ]
}

background.js:

var test = "test";

content.js:

test = "testA";

你想要的是不可能的。后台脚本和内容脚本在不同的上下文中执行,在某些情况下,在不同的进程中执行。不可能在两个上下文之间直接共享一个变量。但是,您可以共享信息。

.storage.local exists to be able to store information within your extension in a way that is accessible to all of your scripts.1 Data stored in .storage.local persists through the browser being restarted. You can set a value, using .storage.local.set(), within your background.js and then get the value, using .storage.local.get() 来自您的 content.js.

上面链接的 MDN 页面上有使用 .storage.local 的示例。还有很多 Stack Overflow questions/answers which provide examples.


1.除了您插入到页面上下文中的脚本。这些不是内容脚本,但您可以使用内容脚本插入它们。它们是您用来访问通常存在于页面脚本中的变量和函数的方法 运行 在网页上。

另一种方法是使用 browser.runtime.sendMessage() API.

在内容脚本中:

document.addEventListener('DOMContentLoaded', function() {
    browser.runtime.sendMessage({
        type: "getText"
    }).then(function(message) {
        console.log("Value of text is: ", message.result);
    });

    browser.runtime.sendMessage({
        type: "setText",
        value: "Yes, I can get you!!"
    }).then(function(message) {
        console.log("New value of text is: ", message.result);
    });
});

在后台脚本中:

var text = "Can you get me??";

browser.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.type == "getText") {
        sendResponse({result: text});
    } else if (request.type == "setText") {
        text = request.value;
        sendResponse({result: text});
    }
});

在浏览器控制台中,我们可以看到输出为:

Value of text is:  Can you get me??
New value of text is:  Yes, I can get you!!