WebExtension:如何在浏览器操作中访问后台脚本

WebExtension: How can I access the background script in my browser action

我对 WebExtension 完全陌生(尝试在 Firefox 下使用它们)。我写了一个浏览器动作。为了保持持久状态,我想我必须实现一个后台脚本。

如何从浏览器操作脚本访问后台脚本中定义的变量?

或者后台脚本可以包含浏览器操作状态的假设是否错误?

好的,知道了。我找到了一个好的开始 here and here.

我使用消息发布在我的浏览器操作和后台脚本之间进行通信。

想一想您可以在浏览器操作弹出窗口中操作并且游戏状态在后台脚本中的游戏。这是从后台脚本获取硬币数量(玩家金钱)到浏览器操作的示例:

浏览器操作:

var _playerCoins = 0;

// I connect a 'port' with the name 'getCoins'.
var _port = chrome.runtime.connect({name: "getCoins"});

// This is the message that is called if the other side posts a message via the port.
// The background script puts the current amount of coins into the message
_port.onMessage.addListener(function(msg) {
    // Save the number of coins in a local variable
    _playerCoins = msg;
    // Display number of coins on my browser action html page
    document.getElementById("coins").innerHTML="Coins: " + _playerCoins;
});

后台脚本:

// Add a listener for port connections
chrome.runtime.onConnect.addListener(function(port) {
    // If there is a 'getCoins' connection coming in...
    if(port.name == "getCoins") {
        // ...add a listener that is called when the other side posts a message on the port.
        port.onMessage.addListener(function(msg) {
            port.postMessage(_playerCoins);
        });
    }
}