我是WebExtension的新手(尝试在Firefox下使用它们)。我写了一个浏览器动作。为了保持持久状态,我认为我必须实现后台脚本。
如何从浏览器操作脚本中调用后台脚本中定义的变量?
或者假设背景脚本可以包含浏览器操作的状态是错误的吗?
答案 0 :(得分:1)
我使用邮件发布功能在浏览器操作和后台脚本之间进行通信。
想象一下你可以在浏览器动作弹出窗口中操作的游戏,游戏状态在后台脚本中。以下是从后台脚本到浏览器操作获取硬币数量(玩家资金)的示例:
浏览器的动作:
let myView = UIView()
view.backgroundColor = UIColor.redColor()
self.view.addSubview(view)
let topConstraint = NSLayoutConstraint(item: myView,
attribute: .Top,
relatedBy: .Equal,
toItem: self.topLayoutGuide,
attribute: .Bottom,
multiplier: 1,
constant: 0)
let trailingConstraint = NSLayoutConstraint(item: self.view,
attribute: .TrailingMargin,
relatedBy: .Equal,
toItem: myView,
attribute: .Trailing,
multiplier: 1,
constant: 0)
let bottomConstraint = NSLayoutConstraint(item: self.bottomLayoutGuide,
attribute: .Top,
relatedBy: .Equal,
toItem: myView,
attribute: .Bottom,
multiplier: 1,
constant: 0)
let widthConstraint = NSLayoutConstraint(item: myView,
attribute: .Width,
relatedBy: .Equal,
toItem: nil,
attribute: .NotAnAttribute,
multiplier: 1,
constant: 300)
self.view.addConstraints([trailingConstraint])
view.addConstraints([topConstraint, bottomConstraint, widthConstraint])
后台脚本:
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;
});