I am trying to do cross-domain communication using postMessage between a page (on example1.com) and an iframe on the same page that is on example2.com
When the iframe is done loading, it sends a postMessage to the parent page using the following command:
parent.postMessage('hello parent', 'http://example1.com'); //this command works
In the event handler for postMessage in the parent page (on example1.com), I send a response back to the child page (example2.com) using the following function:
//this function is defined in example1.com:
function receiveMessage(event){
if (event.origin == "http://example2.com"){
console.log('Message Received from iframe'); //this line works
event.source.postMessage('hello to you too', event.origin); //this line does not work
}
}
For some reason, the event handler for postMessage in the iframe is not triggered.
//this function is defined in example2.com
function receiveMessage(event){
if (event.origin == "http://example1.com"){ // I even tried removing this check to no avail
console.log('Message Received from parent'); //this line works
}
}
When the parent tries to send a message to the iframe it simply returns undefined.
Any help is appreciated!
EDIT:
I tried changing the following line in example1.com's receiveMessage event:
event.source.postMessage('hello to you too', event.origin);
to this:
event.source.postMessage('hello to you too', 'http://example2.com');
But I get this following error:
Unable to post message to http://example2.com. Recipient has origin http://example1.com
Why is event.origin evaluating to http://example1.com when it is receiving a message from example2.com?
example1.com is trying to send itself a postMessage. This ought to be the source of the error