From long back sending messages between windows was only possible if the windows used the same protocol, port, and host. The
postMessage() method helps to solve this issue by providing a way to securely pass messages across domains.
In this blog post I’m going to explain how to use the
postMessage() method to communicate between a controller window and a receiver window running different domains.
The postMessage() method accepts two parameters.
- message – A string or object that will be sent to the receiving window.
- targetOrigin – The URL of the window that the message is being sent to. The protocol, port and hostname of the target window must match this parameter for the message to be sent. Specifying “*” will match any URL however this is strongly discouraged for security reasons.
This method should be called on the window that the message is being sent to.
Set Event Listener on the Receiver Window
When postMessage() is executed successfully on sender window a MessageEvent will be fired on the receiving window. The event passed into the listener callback has a property called data that can be used to access the string or object that was sent by postMessage().
var message = m.data;
Here Data is a property which holds string or abject passed by postmessage().
Set postMessage on the Sender Window
Browser Support For postMessage
Few security considerations that need to be taken into account when using postMessage() are as below.
- First make sure that you are always specifying full URLs as your targetOrigin parameter and not just using wildcards (*), otherwise you could accidently send data to a malicious website..
- postMessage() is a really handy tool to have in your toolbox, especially if you do a lot of work with iframes.