Understanding postMessage for Secure Cross-Origin Communication

Diego Caceres
Pragma
Published in
3 min readAug 5, 2023

--

Hello coders 🖖🏻, In this blog post, I will introduce you to the postMessage API, an amazing yet little-known feature for secure cross-origin communication. If you have any feedback, I would love to hear it!

Problem Statement

Imagine you have a web application that needs to communicate between different windows or iframes. For instance, you may have a main application running in the parent window and a child window or iframe that needs to exchange data with the parent. Due to the same-origin policy, direct communication between these windows can be challenging and insecure. This is where postMessage comes into play, allowing secure and reliable communication between different browsing contexts.

What is postMessage?

postMessage is a method that allows you to send messages from one window to another in a secure and controlled manner. It is especially useful for communication between a parent window and a child window, or between iframes and their parent document. By using postMessage, we can securely circumvent the same-origin policy and ensure that our data exchanges are safe and reliable.

Practical Example

Let’s consider a practical example. Suppose you have a main application running in a parent window and you open a child window to display some additional information. You want the child window to send data back to the parent window after some processing.

Sending a Message from the Parent Window

Here’s how you can send a message from the parent window to the child window:

// Open a new window
const childWindow = window.open('child.html', 'Child Window');

// Wait until the child window is fully loaded
childWindow.addEventListener('load', () => {
// Send a message to the child window
const message = 'Hello from the parent window!';
const targetOrigin = 'https://your-domain.com';
childWindow.postMessage(message, targetOrigin);
});

Receiving a Message in the Child Window

In the child window, you can receive and process the message as follows:

window.addEventListener('message', (event) => {
// Validate the origin of the message
if (event.origin !== 'https://your-domain.com') return;

// Process the received message
console.log('Message received from parent window:', event.data);
});

Sending a Response from the Child Window

Similarly, the child window can send a response back to the parent window:

// Assuming the parent window reference is available
const parentWindow = window.opener;

// Send a message back to the parent window
const responseMessage = 'Hello from the child window!';
const targetOrigin = 'https://your-domain.com';
parentWindow.postMessage(responseMessage, targetOrigin);

Receiving the Response in the Parent Window

In the parent window, you can receive and process the response as follows:

window.addEventListener('message', (event) => {
// Validate the origin of the message
if (event.origin !== 'https://your-domain.com') return;

// Process the received response
console.log('Response received from child window:', event.data);
});

Key Considerations

  • Validate Origins: Always validate the origin of the messages you receive. This ensures that you only accept messages from trusted sources.
  • Avoid Using ‘*’: Avoid using ‘*’ as the targetOrigin to prevent malicious sites from intercepting your messages.
  • Secure Data Handling: Ensure that the data being sent and received is handled securely to prevent data leaks or unauthorized access.

By following these best practices, you can effectively use postMessage to enable secure and reliable cross-origin communication in your web applications.

I hope that can enjoy this article. Whatever question can you text me on Google :).

--

--

Diego Caceres
Pragma

Software developer / Engineer. Learner of the life 🍃