I'm trying to implement communication with postMessage. There is the main page which opens a popup with an iframe which comes from a different domain. This works fine so far but I want to catch the following error which occurs when I open the iFrame with a wrong origin.
Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('myOriginURL') does not match the recipient window's origin ('myWindowsOrigin').
origin = 'http://www.myorigin.ch';
if (window.postMessage) {
try {
top.postMessage('hello', origin);
}
catch(ex) {
alert('an error occured');
}
}
the problem is that the code never runs into the catch block. Interesting part is that chrome shows an error in the console while all other major browser just don't do anything (no alert, no error)
How can I handle the error in the postMessage?
A malicious site can change the location of the window without your knowledge, and therefore it can intercept the data sent using postMessage .
In action: iframeAn <iframe> tag hosts a separate embedded window, with its own separate document and window objects. We can access them using properties: iframe.
postMessage() sends a message back to the main page. The two ends can listen to messages from the other using window.
The postMessage() function is asynchronous, meaning it will return immediately. So you can not do synchronous communication with it. In your example, the posted message will vanish in the void, because there is no listener for the message event at the time the postMessage() function is executed.
I think this is made on purpose. Your context should not know if the message was sent successfully, or not (for security purposes)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With