Self.port is undefined

只谈情不闲聊 提交于 2019-12-11 20:54:35

问题


I have an iframe in popup.html,having id = Receiver, which receives and posts messages.

The below code is from 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();
}

The code from main.js is :

main_panel.on("show", function() {
    main_panel.port.emit("show", UrlActiveTab, TitleActiveTab);
});

Now, I have 2 questions:
1.)Whenever, it receives the message, myApp.CloseIt() is fired. But the console says that self.port is undefined. I have tried using addon.port that also gives error.
2.) If the myApp.sendDetails() is called, it alerts the value of 'arr' as blank, despite being a global array. Why so?

EDITED: Panel constructor code :

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
        });
    }
}

回答1:


Panels are considered trusted content, because you own them. A side effect of this is that the messaging API is available through the addon global, instead of self as is the case for plain content scripts.



来源:https://stackoverflow.com/questions/24119238/self-port-is-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!