Table of contents
1.
Introduction
2.
Components
3.
Example
3.1.
Test Run
4.
Frequently Asked Questions
5.
Conclusion
Last Updated: Mar 27, 2024
Easy

Window.postMessage()

Author GAZAL ARORA
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Cross-domain communication (also known as cross-origin communication) can be complex and dangerous. However, HTML5 has a helpful and sometimes ignored feature called window.postMessage(), which is safe when used correctly.

The window.postMessage() method allows cross-origin communication between Window objects, such as between a page and a pop-up it created or a page and an iframe it contains.

Scripts on different pages usually are allowed to communicate with one another if and only if the pages they come from have the same protocol, port number, and hostname (also known as the "same-origin policy"). window.postMessage() provides a secure way to get around this restriction in a controlled manner.

In general, one window can receive a reference to another (e.g., via targetWindow = window.opener) and then use targetWindow.postMessage to send a MessageEvent() to it. The receiving window is, therefore, free to deal with the situation. The event object exposes the arguments supplied to window.postMessage() (i.e., the "message") to the receiving window.

Let's learn more about the targetWindow,

The window that will receive the message is called the targetWindow. Obtaining such a reference can be done in a variety of ways, including

Components

The following are the two necessary components:

  1. window.postMessage(): to send message
  2. window.addEventListener(“message”, callback): to receive and process the message.

 

Syntax

postMessage(message, targetOrigin)
postMessage(message, targetOrigin, [transfer])

Arguments

message

The information is to be transmitted to the other window. The structured clone algorithm is used to encode the data. Functions cannot be sent as messages. The structured clone algorithm does not allow functions. However, you can send a wide range of data items to the target window without having to encode them beforehand.

targetOrigin

Specifies the origin of targetWindow, either as the literal string "*" or as a URI. It is the URI of the receiver’s page.

If the scheme, hostname, or port of targetWindow's document do not match those supplied in targetOrigin when the event is scheduled to be sent, the event will not be dispatched. Only if all of the three matches, the event will be dispatched. 

This mechanism allows you to control where messages are sent. For example, suppose postMessage() is used to send a password. In that case, this argument must be a URI with the exact origin as the intended receiver of the password-containing message to prevent the password from being intercepted by a malicious third party.

Always provide a targetOrigin. If you know where the receiver's domain is, provide it rather than *. If you don't specify a target, the data you send will be visible to any malicious site that is interested.

Note: If “*” is used as the targetOrigin, the message could be from anyone.

For example, if we want to send a message from https://www.codingninjas.com to https://campus.codingninjas.com, the targetOrigin would be https://campus.codingninjas.com, and the recipient’s domain would be https://campus.codingninjas.com as well.

transfer 

It is a set of transferable objects that are sent together with the message. These objects are now owned by the destination side and are no longer useable by the sender side.

Example

Let’s create two web pages named PageA.html and PageB.html such that:

  • PageB.html will be a pop-up. 
  • PageA.html will send a message to PageB.html.

 

PageA

<!DOCTYPE html>
<html>
<head>
    <title>Window Post Message Test</title>
 <meta charset="utf-8" />
<script>
var childwin;
const childname = "popup";
function openChild() {
childwin = window.open('PageB.html', childname, 'height=300px, width=500px');
 
}
function sendMessage(){
    let msg={pName : "Bob", pAge: "35"};
    // In production, DO NOT use '*', use toe target domain
    childwin.postMessage(msg,'*')// childwin is the targetWindow
    childwin.focus();
}
</script>
</head>
<body>
    <form>
        <fieldset>
            <input type="button" id="btnopen" value="Open child" onclick="openChild();" />
            <input type="button" id="btnSendMsg" value="Send Message" onclick="sendMessage();" />
        </fieldset>
    </form>
</body>
</html>

 

PageB

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <script>

// It allows window to listen for a postMessage.
    window.addEventListener("message", (event)=>{

// To verify the targetOrigin matches this window's domain.
        let txt=document.querySelector('#txtMsg');
        txt.value=`Name is ${event.data.pName} Age is  ${event.data.pAge}` ;
     
    });
function closeMe() {
        try {
window.close();
        } catch (e) { console.log(e) }
        try {
self.close();
        } catch (e) { console.log(e) }
}
    </script>
</head>
<body>
    <form>
        <h1>Recipient of postMessage</h1>
            <fieldset>
                <input type="text" id="txtMsg" />
                <input type="button" id="btnCloseMe" value="Close me" onclick="closeMe();" />
            </fieldset>
   
    </form>
</body>
</html>

Test Run

On running PageA.html. You will find

Click the "Open child" button on PageA.html. This brings up the pop-up window.

 

On clicking the "Send Message" button, the pop-up Window receives the below-written message.


Let’s understand what is Happening

When you select "Send Message," an Object is delivered to the recipient page using the window reference, childWindow, created during window.open().

On clicking the “Send Message” button, the message will be received by the pop-up window.

childWindow.postMessage(msg,"*" ): 

  • Once again, do not use "*" for other than for testing. The targetOrigin should be the domain of the recipient page.
  • The receiver window's Event Listener receives the message in an "event" parameter.

The callback function processes the message.

  • The message is stored in event.data.
  • The targetOrigin is stored in event.origin.

Frequently Asked Questions

1. What is window postMessage () used for?
The window. postMessage() method is very useful. It allows for cross-origin communication between Window objects. For example, it allowed communication between a page and a pop-up it created or a page and an iframe contained within it.

 

2. How do I view Windows postMessage?
There is no network traffic in postMessage because everything happens between frames and windows on the same machine. You can use console.log(e) to view Windows postMessage. It calls inside your postMessage handlers so you can see the results in the dev tools console.

 

3. Is window postMessage secure?
Cross-site scripting attacks can be launched by acting on a message without first confirming its source. postMessage is typically thought to be quite safe as long as the programmer double-checks the message's origin and source. 

Conclusion

In this article, we learned about Window.postMessage(). We learned that the window.postMessage() method allows cross-origin communication between Window objects.

Window.postMessage is safe as long as the programmer double-checks the message's origin and source. 

We learned that one window could receive a reference to another (e.g., via targetWindow = window.opener) and then use targetWindow.postMessage to send a MessageEvent() to it. The receiving window is, therefore, free to deal with the situation. The event object exposes the arguments supplied to window.postMessage() (i.e., the "message") to the receiving window.

 

Now you are all set to safely communicate between your Window objects on your website—design amazing websites.

 

Happy Coding!.

You can use Coding Ninjas Studio to practice various DSA questions asked in the interviews. It will help you in mastering effective coding techniques, and you will also get interview experiences with people working in big companies.

 

Live masterclass