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 abc.com can communicate with a page from xyz.com.

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

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <button id="send">Send Message</button> <iframe id="receiver" src="https://www.2braces.com/data-structures/demo"> <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 Wikimass.com!', 'https://www.2braces.com'); } btn.addEventListener('click', sendMessage); } </script> </body> </html>

Syntax

targetWindow.postMessage(message, targetOrigin)

Parameter Values

ValueTypeExplanation
targetWindowRequiredA reference to the window that will receive the message.
Methods for obtaining such a reference include:
window.open - 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.

Reminder

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