Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Revision 978521 of Window.postMessage()

  • Revision slug: Web/API/Window/postMessage
  • Revision title: Window.postMessage()
  • Revision id: 978521
  • Created:
  • Creator: groovecoder
  • Is current revision? No
  • Comment link message footnote citation to Browser Compatibility footnote

Revision Content

{{ApiRef}}

The window.postMessage method safely enables cross-origin communication. Normally, scripts on different pages are allowed to access each other if and only if the pages that executed them are at locations with the same protocol (usually both https), port number (443 being the default for https), and host (modulo document.domain being set by both pages to the same value). window.postMessage provides a controlled mechanism to circumvent this restriction in a way which is secure when properly used.

The window.postMessage method, when called, causes a {{domxref("MessageEvent")}} to be dispatched at the target window when any pending script that must be executed completes (e.g., remaining event handlers if window.postMessage is called from an event handler, previously-set pending timeouts, etc.) The {{domxref("MessageEvent")}} has the type message, a data property which is set to the value of the first argument provided to window.postMessage, an origin property corresponding to the origin of the main document in the window calling window.postMessage at the time window.postMessage was called, and a source property which is the window from which window.postMessage is called. (Other standard properties of events are present with their expected values.)

Syntax

otherWindow.postMessage(message, targetOrigin, [transfer]);
otherWindow
A reference to another window; such a reference may be obtained, for example, using the contentWindow property of an iframe element, the object returned by window.open, or by named or numeric index on window.frames.
message
Data to be sent to the other window. The data is serialized using the structured clone algorithm. This means you can pass a broad variety of data objects safely to the destination window without having to serialize them yourself. [1]
targetOrigin
Specifies what the origin of otherWindow must be for the event to be dispatched, either as the literal string "*" (indicating no preference) or as a URI. If at the time the event is scheduled to be dispatched the scheme, hostname, or port of otherWindow's document does not match that provided in targetOrigin, the event will not be dispatched; only if all three match will the event be dispatched. This mechanism provides control over where messages are sent; for example, if postMessage was used to transmit a password, it would be absolutely critical that this argument be a URI whose origin is the same as the intended receiver of the message containing the password, to prevent interception of the password by a malicious third party. Always provide a specific targetOrigin, not *, if you know where the other window's document should be located. Failing to provide a specific target discloses the data you send to any interested malicious site.
transfer {{optional_Inline}}
Is a sequence of {{domxref("Transferable")}} objects that are transferred with the message. The ownership of these objects is given to the destination side and they are no longer usable on the sending side.

The dispatched event

otherWindow can listen for dispatched messages by executing the following JavaScript:

window.addEventListener("message", receiveMessage, false);

function receiveMessage(event)
{
  if (event.origin !== "https://example.org:8080")
    return;

  // ...
}

The properties of the dispatched message are:

data
The object passed from the other window.
origin
The origin of the window that sent the message at the time postMessage was called. This string is the concatenation of the protocol and "://", the host name if one exists, and ":" followed by a port number if a port is present and differs from the default port for the given protocol. Examples of typical origins are https://example.org (implying port 443), https://example.net (implying port 80), and https://example.com:8080. Note that this origin is not guaranteed to be the current or future origin of that window, which might have been navigated to a different location since postMessage was called.
source
A reference to the window object that sent the message; you can use this to establish two-way communication between two windows with different origins.

Security concerns

If you do not expect to receive messages from other sites, do not add any event listeners for message events. This is a completely foolproof way to avoid security problems.

If you do expect to receive messages from other sites, always verify the sender's identity using the origin and possibly source properties. Any window (including, for example, https://evil.example.com) can send a message to any other window, and you have no guarantees that an unknown sender will not send malicious messages. Having verified identity, however, you still should always verify the syntax of the received message. Otherwise, a security hole in the site you trusted to send only trusted messages could then open a cross-site scripting hole in your site.

Always specify an exact target origin, not *, when you use postMessage to send data to other windows. A malicious site can change the location of the window without your knowledge, and therefore it can intercept the data sent using postMessage.

Example

/*
 * In window A's scripts, with A being on <https://example.com:8080>:
 */

var popup = window.open(...popup details...);

// When the popup has fully loaded, if not blocked by a popup blocker:

// This does nothing, assuming the window hasn't changed its location.
popup.postMessage("The user is 'bob' and the password is 'secret'",
                  "https://secure.example.net");

// This will successfully queue a message to be sent to the popup, assuming
// the window hasn't changed its location.
popup.postMessage("hello there!", "https://example.org");

function receiveMessage(event)
{
  // Do we trust the sender of this message?  (might be
  // different from what we originally opened, for example).
  if (event.origin !== "https://example.org")
    return;

  // event.source is popup
  // event.data is "hi there yourself!  the secret response is: rheeeeet!"
}
window.addEventListener("message", receiveMessage, false);
/*
 * In the popup's scripts, running on <https://example.org>:
 */

// Called sometime after postMessage is called
function receiveMessage(event)
{
  // Do we trust the sender of this message?
  if (event.origin !== "https://example.com:8080")
    return;

  // event.source is window.opener
  // event.data is "hello there!"

  // Assuming you've verified the origin of the received message (which
  // you must do in any case), a convenient idiom for replying to a
  // message is to call postMessage on event.source and provide
  // event.origin as the targetOrigin.
  event.source.postMessage("hi there yourself!  the secret response " +
                           "is: rheeeeet!",
                           event.origin);
}

window.addEventListener("message", receiveMessage, false);

Notes

Any window may access this method on any other window, at any time, regardless of the location of the document in the window, to send it a message. Consequently, any event listener used to receive messages must first check the identity of the sender of the message, using the origin and possibly source properties. This cannot be overstated: Failure to check the origin and possibly source properties enables cross-site scripting attacks.

As with any asynchronously-dispatched script (timeouts, user-generated events), it is not possible for the caller of postMessage to detect when an event handler listening for events sent by postMessage throws an exception.

The value of the origin property of the dispatched event is not affected by the current value of document.domain in the calling window.

For IDN host names only, the value of the origin property is not consistently Unicode or punycode; for greatest compatibility check for both the IDN and punycode values when using this property if you expect messages from IDN sites. This value will eventually be consistently IDN, but for now you should handle both IDN and punycode forms.

The value of the origin property when the sending window contains a javascript: or data: URL is the origin of the script that loaded the URL.

Using window.postMessage in extensions {{Non-standard_inline}}

window.postMessage is available to JavaScript running in chrome code (e.g., in extensions and privileged code), but the source property of the dispatched event is always null as a security restriction. (The other properties have their expected values.) The targetOrigin argument for a message sent to a window located at a chrome: URL is currently misinterpreted such that the only value which will result in a message being sent is "*". Since this value is unsafe when the target window can be navigated elsewhere by a malicious site, it is recommended that postMessage not be used to communicate with chrome: pages for now; use a different method (such as a query string when the window is opened) to communicate with chrome windows. Lastly, posting a message to a page at a file: URL currently requires that the targetOrigin argument be "*". file:// cannot be used as a security restriction; this restriction may be modified in the future.

Specifications

Specification Status Comment
{{SpecName('HTML WHATWG', "#dom-window-postmessage", "window.postMessage")}} {{Spec2('HTML WHATWG')}} No change from {{SpecName('HTML5 Web Messaging')}}
{{SpecName('HTML5 Web Messaging', '#dom-window-postmessage', 'window.postMessage')}} {{Spec2('HTML5 Web Messaging')}} Initial definition.

Browser compatibility

{{CompatibilityTable}}

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support 1.0 {{CompatGeckoDesktop(6.0)}}[1]
{{CompatGeckoDesktop(8.0)}}[2]
8.0[3]
10.0[4]
9.5 4.0
transfer argument {{CompatUnknown}} {{CompatGeckoDesktop(20.0)}} {{CompatNo}} {{CompatUnknown}} {{CompatUnknown}}
Feature Android Firefox Mobile (Gecko) IE Phone Opera Mobile Safari Mobile
Basic support {{CompatVersionUnknown}} {{CompatGeckoDesktop(6.0)}}[1]
{{CompatGeckoDesktop(8.0)}}[2]
{{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}}
transfer argument {{CompatUnknown}} {{CompatGeckoMobile(20.0)}} {{CompatNo}} {{CompatUnknown}} {{CompatUnknown}}

[1] Prior to Gecko 6.0 {{geckoRelease("6.0")}}, the message parameter must be a string. Starting in Gecko 6.0 {{geckoRelease("6.0")}}, the message parameter is serialized using the structured clone algorithm. This means you can pass a broad variety of data objects safely to the destination window without having to serialize them yourself.

[2] Gecko 8.0 introduced support for sending {{domxref("File")}} and {{domxref("FileList")}} objects between windows. This is only allowed if the recipient's principal is contained within the sender's principal for security reasons.

[3] IE8 and IE9 only support it for {{HTMLElement("frame")}} and {{HTMLElement("iframe")}}.

[4] IE10 has important limitations: see this article for details.

See also

Revision Source

<div>{{ApiRef}}</div>

<p>The <strong><code>window.postMessage</code></strong> method safely enables cross-origin communication. Normally, scripts on different pages are allowed to access each other if and only if the pages that executed them are at locations with the same protocol (usually both <code>https</code>), port number (<code>443</code> being the default for <code>https</code>), and host (modulo <a href="/en-US/docs/DOM/document.domain">document.domain</a> being set by both pages to the same value). <code>window.postMessage</code> provides a controlled mechanism to circumvent this restriction in a way which is secure when properly used.</p>

<p>The <code>window.postMessage</code> method, when called, causes a {{domxref("MessageEvent")}} to be dispatched at the target window when any pending script that must be executed completes (e.g., remaining event handlers if <code>window.postMessage</code> is called from an event handler, previously-set pending timeouts, etc.) The {{domxref("MessageEvent")}} has the type <code>message</code>, a <code>data</code> property which is set to the value of the first argument provided to <code>window.postMessage</code>, an <code>origin</code> property corresponding to the origin of the main document in the window calling <code>window.postMessage</code> at the time <code>window.postMessage</code> was called, and a <code>source</code> property which is the window from which <code>window.postMessage</code> is called. (Other standard properties of events are present with their expected values.)</p>

<h2 id="Syntax">Syntax</h2>

<pre class="syntaxbox">
<em>otherWindow</em>.postMessage(<em>message</em>, <em>targetOrigin</em>, [<em>transfer</em>]);</pre>

<dl>
	<dt><code><em>otherWindow</em></code></dt>
	<dd>A reference to another window; such a reference may be obtained, for example, using the <code>contentWindow</code> property of an <code>iframe</code> element, the object returned by <a href="/en-US/docs/DOM/window.open">window.open</a>, or by named or numeric index on <a href="/en-US/docs/DOM/window.frames">window.frames</a>.</dd>
	<dt><code><em>message</em></code></dt>
	<dd>Data to be sent to the other window. <code>The data</code> is serialized using <a href="/en-US/docs/DOM/The_structured_clone_algorithm">the structured clone algorithm</a>. This means you can pass a broad variety of data objects safely to the destination window without having to serialize them yourself. [<a href="/en-US/docs/">1</a>]</dd>
	<dt><code><em>targetOrigin</em></code></dt>
	<dd>Specifies what the origin of <code>otherWindow</code> must be for the event to be dispatched, either as the literal string <code>"*"</code> (indicating no preference) or as a URI. If at the time the event is scheduled to be dispatched the scheme, hostname, or port of <code>otherWindow</code>'s document does not match that provided in <code>targetOrigin</code>, the event will not be dispatched; only if all three match will the event be dispatched. This mechanism provides control over where messages are sent; for example, if <code>postMessage</code> was used to transmit a password, it would be absolutely critical that this argument be a URI whose origin is the same as the intended receiver of the message containing the password, to prevent interception of the password by a malicious third party. <strong>Always provide a specific <code>targetOrigin</code>, not <code>*</code>, if you know where the other window's document should be located. Failing to provide a specific target discloses the data you send to any interested malicious site.</strong></dd>
	<dt><code><em><strong>transfer</strong></em></code> {{optional_Inline}}</dt>
	<dd>Is a sequence of {{domxref("Transferable")}} objects that are transferred with the message. The ownership of these objects is given to the destination side and they are no longer usable on the sending side.</dd>
</dl>

<h2 id="The_dispatched_event">The dispatched event</h2>

<p><code>otherWindow</code> can listen for dispatched messages by executing the following JavaScript:</p>

<pre class="brush: js">
window.addEventListener("message", receiveMessage, false);

function receiveMessage(event)
{
  if (event.origin !== "https://example.org:8080")
    return;

  // ...
}
</pre>

<p>The properties of the dispatched message are:</p>

<dl>
	<dt><code>data</code></dt>
	<dd>The object passed from the other window.</dd>
	<dt><code>origin</code></dt>
	<dd>The <a href="/en-US/docs/Origin">origin</a> of the window that sent the message at the time <code>postMessage</code> was called. This string is the concatenation of the protocol and "://", the host name if one exists, and ":" followed by a port number if a port is present and differs from the default port for the given protocol. Examples of typical origins are <code class="nowiki">https://example.org</code> (implying port <code>443</code>), <code class="nowiki">https://example.net</code> (implying port <code>80</code>), and <code class="nowiki">https://example.com:8080</code>. Note that this origin is <em>not</em> guaranteed to be the current or future origin of that window, which might have been navigated to a different location since <code>postMessage</code> was called.</dd>
	<dt><code>source</code></dt>
	<dd>A reference to the <code><a href="/en-US/docs/DOM/window">window</a></code> object that sent the message; you can use this to establish two-way communication between two windows with different origins.</dd>
</dl>

<h2 id="Security_concerns">Security concerns</h2>

<p><strong>If you do not expect to receive messages from other sites, <em>do not</em> add any event listeners for <code>message</code> events.</strong> This is a completely foolproof way to avoid security problems.</p>

<p>If you do expect to receive messages from other sites, <strong>always verify the sender's identity</strong> using the <code>origin</code> and possibly <code>source</code> properties. Any window (including, for example, <code class="nowiki">https://evil.example.com</code>) can send a message to any other window, and you have no guarantees that an unknown sender will not send malicious messages. Having verified identity, however, you still should <strong>always verify the syntax of the received message</strong>. Otherwise, a security hole in the site you trusted to send only trusted messages could then open a cross-site scripting hole in your site.</p>

<p><strong>Always specify an exact target origin, not <code>*</code>, when you use <code>postMessage</code> to send data to other windows.</strong> A malicious site can change the location of the window without your knowledge, and therefore it can intercept the data sent using <code>postMessage</code>.</p>

<h2 id="Example">Example</h2>

<pre class="brush: js">
/*
 * In window A's scripts, with A being on &lt;https://example.com:8080&gt;:
 */

var popup = window.open(...popup details...);

// When the popup has fully loaded, if not blocked by a popup blocker:

// This does nothing, assuming the window hasn't changed its location.
popup.postMessage("The user is 'bob' and the password is 'secret'",
                  "https://secure.example.net");

// This will successfully queue a message to be sent to the popup, assuming
// the window hasn't changed its location.
popup.postMessage("hello there!", "https://example.org");

function receiveMessage(event)
{
  // Do we trust the sender of this message?  (might be
  // different from what we originally opened, for example).
  if (event.origin !== "https://example.org")
    return;

  // event.source is popup
  // event.data is "hi there yourself!  the secret response is: rheeeeet!"
}
window.addEventListener("message", receiveMessage, false);
</pre>

<pre class="brush: js">
/*
 * In the popup's scripts, running on &lt;https://example.org&gt;:
 */

// Called sometime after postMessage is called
function receiveMessage(event)
{
  // Do we trust the sender of this message?
  if (event.origin !== "https://example.com:8080")
    return;

  // event.source is window.opener
  // event.data is "hello there!"

  // Assuming you've verified the origin of the received message (which
  // you must do in any case), a convenient idiom for replying to a
  // message is to call postMessage on event.source and provide
  // event.origin as the targetOrigin.
  event.source.postMessage("hi there yourself!  the secret response " +
                           "is: rheeeeet!",
                           event.origin);
}

window.addEventListener("message", receiveMessage, false);
</pre>

<h3 id="Notes">Notes</h3>

<p>Any window may access this method on any other window, at any time, regardless of the location of the document in the window, to send it a message. Consequently, any event listener used to receive messages <strong>must</strong> first check the identity of the sender of the message, using the <code>origin</code> and possibly <code>source</code> properties. This cannot be overstated: <strong>Failure to check the <code>origin</code> and possibly <code>source</code> properties enables cross-site scripting attacks.</strong></p>

<p>As with any asynchronously-dispatched script (timeouts, user-generated events), it is not possible for the caller of <code>postMessage</code> to detect when an event handler listening for events sent by <code>postMessage</code> throws an exception.</p>

<p>The value of the <code>origin</code> property of the dispatched event is not affected by the current value of <code>document.domain</code> in the calling window.</p>

<p>For IDN host names only, the value of the <code>origin</code> property is not consistently Unicode or punycode; for greatest compatibility check for both the IDN and punycode values when using this property if you expect messages from IDN sites. This value will eventually be consistently IDN, but for now you should handle both IDN and punycode forms.</p>

<p>The value of the <code>origin</code> property when the sending window contains a <code>javascript:</code> or <code>data:</code> URL is the origin of the script that loaded the URL.</p>

<h3 id="Using_window.postMessage_in_extensions_Non-standard_inline">Using window.postMessage in extensions {{Non-standard_inline}}</h3>

<p><code>window.postMessage</code> is available to JavaScript running in chrome code (e.g., in extensions and privileged code), but the <code>source</code> property of the dispatched event is always <code>null</code> as a security restriction. (The other properties have their expected values.) The <code>targetOrigin</code> argument for a message sent to a window located at a <code>chrome:</code> URL is currently misinterpreted such that the only value which will result in a message being sent is <code>"*"</code>. Since this value is unsafe when the target window can be navigated elsewhere by a malicious site, it is recommended that <code>postMessage</code> not be used to communicate with <code>chrome:</code> pages for now; use a different method (such as a query string when the window is opened) to communicate with chrome windows. Lastly, posting a message to a page at a <code>file:</code> URL currently requires that the <code>targetOrigin</code> argument be <code>"*"</code>. <code>file://</code> cannot be used as a security restriction; this restriction may be modified in the future.</p>

<h2 id="Specifications">Specifications</h2>

<table class="standard-table">
	<tbody>
		<tr>
			<th><strong>Specification</strong></th>
			<th><strong>Status</strong></th>
			<th><strong>Comment</strong></th>
		</tr>
		<tr>
			<td>{{SpecName('HTML WHATWG', "#dom-window-postmessage", "window.postMessage")}}</td>
			<td>{{Spec2('HTML WHATWG')}}</td>
			<td>No change from {{SpecName('HTML5 Web Messaging')}}</td>
		</tr>
		<tr>
			<td>{{SpecName('HTML5 Web Messaging', '#dom-window-postmessage', 'window.postMessage')}}</td>
			<td>{{Spec2('HTML5 Web Messaging')}}</td>
			<td>Initial definition.</td>
		</tr>
	</tbody>
</table>

<h2 id="Browser_compatibility">Browser compatibility</h2>

<p>{{CompatibilityTable}}</p>

<div id="compat-desktop">
<table class="compat-table">
	<tbody>
		<tr>
			<th><strong>Feature</strong></th>
			<th><strong>Chrome</strong></th>
			<th><strong>Firefox (Gecko)</strong></th>
			<th><strong>Internet Explorer</strong></th>
			<th><strong>Opera</strong></th>
			<th><strong>Safari (WebKit)</strong></th>
		</tr>
		<tr>
			<td>Basic support</td>
			<td>1.0</td>
			<td>{{CompatGeckoDesktop(6.0)}}<sup>[1]</sup><br />
			{{CompatGeckoDesktop(8.0)}}<sup>[2]</sup></td>
			<td>8.0<sup>[3]</sup><br />
			10.0<sup>[4]</sup></td>
			<td>9.5</td>
			<td>4.0</td>
		</tr>
		<tr>
			<td><code>transfer</code> argument</td>
			<td>{{CompatUnknown}}</td>
			<td>{{CompatGeckoDesktop(20.0)}}</td>
			<td>{{CompatNo}}</td>
			<td>{{CompatUnknown}}</td>
			<td>{{CompatUnknown}}</td>
		</tr>
	</tbody>
</table>
</div>

<div id="compat-mobile">
<table class="compat-table">
	<tbody>
		<tr>
			<th><strong>Feature</strong></th>
			<th><strong>Android</strong></th>
			<th><strong>Firefox Mobile (Gecko)</strong></th>
			<th><strong>IE Phone</strong></th>
			<th><strong>Opera Mobile</strong></th>
			<th><strong>Safari Mobile</strong></th>
		</tr>
		<tr>
			<td>Basic support</td>
			<td>{{CompatVersionUnknown}}</td>
			<td>{{CompatGeckoDesktop(6.0)}}<sup>[1]</sup><br />
			{{CompatGeckoDesktop(8.0)}}<sup>[2]</sup></td>
			<td>{{CompatVersionUnknown}}</td>
			<td>{{CompatVersionUnknown}}</td>
			<td>{{CompatVersionUnknown}}</td>
		</tr>
		<tr>
			<td><code>transfer</code> argument</td>
			<td>{{CompatUnknown}}</td>
			<td>{{CompatGeckoMobile(20.0)}}</td>
			<td>{{CompatNo}}</td>
			<td>{{CompatUnknown}}</td>
			<td>{{CompatUnknown}}</td>
		</tr>
	</tbody>
</table>
</div>

<p>[1] Prior to Gecko 6.0 {{geckoRelease("6.0")}}, the <code>message</code> parameter must be a string. Starting in Gecko 6.0 {{geckoRelease("6.0")}}, the <code>message</code> parameter is serialized using <a href="/en-US/docs/DOM/The_structured_clone_algorithm">the structured clone algorithm</a>. This means you can pass a broad variety of data objects safely to the destination window without having to serialize them yourself.</p>

<p>[2] Gecko 8.0 introduced support for sending {{domxref("File")}} and {{domxref("FileList")}} objects between windows. This is only allowed if the recipient's principal is contained within the sender's principal for security reasons.</p>

<p>[3] IE8 and IE9 only support it for {{HTMLElement("frame")}} and {{HTMLElement("iframe")}}.</p>

<p>[4] IE10 has important limitations: see this <a href="https://stackoverflow.com/questions/16226924/is-cross-origin-postmessage-broken-in-ie10">article</a> for details.</p>

<h2 id="See_also">See also</h2>

<ul>
	<li><a href="/en-US/docs/DOM/document.domain">Document.domain</a></li>
	<li><a href="/en-US/docs/Web/API/CustomEvent">CustomEvent</a></li>
	<li><a href="/en-US/docs/Code_snippets/Interaction_between_privileged_and_non-privileged_pages">Interaction between privileged and non-privileged pages</a></li>
</ul>
Revert to this revision