0
votes

For starters, I've been trying to allow communication from a page script to a content script. If the docs are accurate, this should be easy. Here's what I'm doing, I believe fully in accordance with https://addons.mozilla.org/en-US/developers/docs/sdk/latest/dev-guide/guides/content-scripts/communicating-with-other-scripts.html#Using%20the%20DOM%20postMessage%20API :

And here's my live test case:

main.js:

exports.main = function() {
    var data = require('sdk/self').data,
            pageMod = require('sdk/page-mod');

    pageMod.PageMod({
        include: '*',
        contentScriptFile: data.url('postMessageRelay.js'),
    });
};

postMessageRelay.js

// Trying with window.addEventListener also doesn't work
document.defaultView.addEventListener('message', function (e) { // e.data, e.origin

    console.log('would be good if it got here:'+e.data);

});
console.log('it gets here at least');

And the JavaScript within a regular HTML file (on a normal remote server, not file or localhost):

try {
    window.postMessage('webappfind', window.location.href);
}
catch(e) {
    alert(e);
}

This really looks like either a full-blown bug for this functionality or a problem with the docs... I had similar problems trying to communicate via custom events so going a little bananas...

1
Your addon code is fine. But your test web page uses window.location.domain (== undefined) as the target origin. - paa
Sorry, had been asked to try that value and forgot that I was linking from it here. I've reverted it back to "window.location.href". But it also doesn't work with * at brett-zamir.me/tests/webappfind2.html though it does work when used from window.open and sometimes when used from an iframe to parent - Brett Zamir

1 Answers

1
votes

Answered in Bug 910972, but leaving it here to for future visitors of SO:

The issue was with the page immediately firing postMessage in the head tag, so the page-mod script isn't even yet attached to the page to listen to the message event. The communication back and forth between page and content scripts as in this example works as long as this timing is taken into consideration