window Methods: postMessage()

By: Dusty Arlia
Published on Saturday, March 22, 2014, 01:03 PM
Last Updated on Tuesday, July 14, 2015 at 12:41 PM
Total Updates: 3

The postMessage() JavaScript window method is used to send asynchronous messages between scripts of different origins. This communication method is defined in HTML5 and is implemented by all current web browsers, including IE8 and later.

This method takes two arguments:

  • The message to send: You can send any primitive value including objects that can be cloned. Certain browsers expect strings, so you might have to make use of JSON.stringify()
  • The origin of the destination: This argument should be a string with the protocol and hostname specified. This is for security purposes. If you don't have any security concerns, you can specify the wildcard string: "*". If the destination has the same origin as your current window, you can specify "/".

If the origins match, calling postMessage() fires the message event at the target Window object. A script in that window can define an event handler (using onmessage()). The handler is passed an event object that has these properties:

  • data: copy of the message
  • source: Window object that sent the message
  • origin: origin URL where the message was sent from

The onmessage() event handler should first check the origin property.

Comments:

Ad: