JavaScript window.postMessage() Method

You are Here:

JavaScript window.postMessage() Method

The window.postMessage() method safely enables cross-origin communication between two pages regardless of their location.

Note: A page from can communicate with a page from

In the following example, we will communicate with a page in (another domain).


HTML Online Editor
<!DOCTYPE html> <html> <body> <button id="send">Send Message</button> <iframe id="receiver" src=""> <p>Your browser does not support iframes.</p> </iframe> <script> window.onload = function(){ var btn = document.getElementById('send'); var receiver = document.getElementById('receiver').contentWindow; function sendMessage(e) { e.preventDefault(); receiver.postMessage('Hello!', ''); } btn.addEventListener('click', sendMessage); } </script> </body> </html>


targetWindow.postMessage(message, targetOrigin)

Parameter Values

targetWindowRequiredA reference to the window that will receive the message.
Methods for obtaining such a reference include: - to spawn a new window and then reference it.
window.opener - to reference the window that spawned this one.
HTMLIFrameElement.contentWindow - to reference an embedded <iframe> from its parent window.
window.parent - to reference the parent window from within an embedded <iframe>
window.frames + an index value
messageRequiredData to be sent to the other window
targetOriginRequiredSpecifies what the origin of targetWindow must be for the event to be dispatched.


Hi Developers, we almost covered 97% of JavaScript Tutorials with examples for quick and easy learning.

We are working to cover every Single Concept in JavaScript.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author