krakenjs / post-robot

Cross domain post-messaging on the client side using a simple listener/client pattern.
Apache License 2.0
741 stars 92 forks source link

No handler found for post message, using in chrome extension #84

Open AlexFree opened 5 years ago

AlexFree commented 5 years ago

i am trying to use post-robot in the chrome extension to make communication between page script and content script. If i return Promise inside 'postRobot.on' i will get error 'No handler found for post message...', but if i just return the value directly then everything is ok.

Inside page script i have:

postRobot.send(window, 'message', {k:0}).then(function (e) {
    alert(e.data);
});

Inside content script i have:

postRobot.on('message', function (e) {
    return new Promise(function (resolve, reject) {
        setTimeout(() => resolve(999), 3000);
    });
    // return 'bla-bla'; // this works ok
});
blmage commented 4 years ago

This is due to the fact that both the content script and the page script of a Chrome extension share the same window, but not the same global variables (see the content scripts documentation).

In your case, when post-robot sends back the result by using postMessage on the event source, the message is first handled by the content script window, on which the listener that was specifically registered to handle it is not accessible, resulting in the error you mentioned.

Not sure if there is any (general) work-around for this (after encountering this I ended up directly using postMessage and addEventListener - in a much less readable fashion), but I would definitely be interested if that could be the case!

datgrog commented 2 years ago

Also interested! But even with the snippet from above what it weird is that the injected_script does indeed get the callback with the result from the listener in the content_script but then throw 3 times both (so 6 errors):

What I don't understand is that still, if my injected_script has a button which fire a postRobot.send, it still works each time, but message above seems to say that the listener is not alive anymore whichs feels like a bug given that it still works.

afeld commented 2 years ago

@angela-tran discovered that this was due to the Cross-Origin-Opener-Policy header being set to same-origin by our server. Not sure if relevant, but sharing just in case.