我在 popup.html 中有一个 iframe,具有 id = Receiver,它接收和发布消息。
以下代码来自 popup.js:
self.port.on("show", function(title, url) {
myApp.initialize(title, url);
});
var arr = new Array();
var myApp = {
initialize: function (url,title){
arr = [];
arr.push(url);
arr.push(title);
var receiver = document.getElementById('Receiver').contentWindow;
receiver.postMessage(arr, "*");
},
sendDetails : function(){
alert("arr :"+arr);
},
closeIt : function(){
self.port.emit("close-it");
}
}
window.addEventListener("message" , receiveMessageOnce, false);
function receiveMessageOnce(event){
myApp.closeIt();
}
main.js 中的代码是:
main_panel.on("show", function() {
main_panel.port.emit("show", UrlActiveTab, TitleActiveTab);
});
现在,我有 2 个问题:
1.) 每当它收到消息时, myApp.CloseIt() 就会被触发。但是控制台说 self.port 是未定义的。我试过使用 addon.port 也会出错。
2.) 如果调用 myApp.sendDetails(),它会将“arr”的值警告为空白,尽管它是一个全局数组。为什么这样?
编辑:面板构造函数代码:
var { ToggleButton } = require('sdk/ui/button/toggle');
const panel = require('sdk/panel');
var main_panel = panel.Panel({
contentURL: data.url("popup.html"),
contentScriptFile: [
data.url('js/jquery-1.10.2.min.js'),
data.url("js/popup.js")
],
width: 350,
height: 400
});
var button = ToggleButton({
id: "myaddon_beta",
label: "My Addon",
icon: {
"16": "./img/icon_main_16.png",
"32": "./img/icon_main_32.png",
"64": "./img/icon_main_64.png"
},
onChange : handleChange
});
function handleChange(state){
currentUrl = tabs.activeTab.url;
currentTitle = tabs.activeTab.title;
if(state.checked){
main_panel.show({
position : button
});
button.state("window", {
checked: false
});
}
}