jQuery PostMessage (Cross-Domain Messaging)

j

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

window.addEventListener(‘message’, function(m)

{

var message = m.data;

});

Here Data is a property which holds string or abject passed by postmessage().

Set postMessage on the Sender Window

<script type=”text/javascript”>

$(document).ready(function ()

{

$.postMessage(‘Postmessage Example’,’http://example.com/’);

})

</script>

Browser Support For postMessage

IE Firefox Chrome Safari Opera
8+ 3.0+ 1.0+ 4.0+ 9.5+

Summary

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.

About the author

trupti.dhoka
By trupti.dhoka

Category