0

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

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

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

4

1 回答 1

1

好的,我知道了。我在这里这里找到了一个好的开始。

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

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

浏览器操作:

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);
        });
    }
}
于 2016-04-08T18:45:25.357 回答