Question

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...

Était-ce utile?

La solution

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

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top