Course contentsShow
← Security
Lesson 1064 of 3,05222. Web Security - Client-Side and SPA SecurityFree lesson

postMessage API and Cross-Origin Communication

Understanding postMessage mechanics, origin checking, and secure cross-window messaging patterns.

postMessage API and Cross-Origin Communication

You'll learn how the postMessage API enables safe cross-origin communication between windows while maintaining security boundaries when used correctly.

What Is postMessage?

Normally, the Same-Origin Policy prevents scripts in one window from accessing another window's data if they have different origins. But what if you need controlled communication between windows or iframes from different origins (like embedding a payment widget)?

The postMessage API is the browser's official solution: a secure messaging system that lets windows send data to each other across origins, but only if both sides explicitly participate.

How It Works

Think of postMessage like sending a letter with a visible return address. The sender posts a message to another window:

// Parent window sends to iframe
iframe.contentWindow.postMessage("Hello", "https://trusted-site.com");

The recipient window listens for messages and must verify the sender's origin:

// Child iframe receives message
window.addEventListener("message", (event) => {
  // CRITICAL: Check the origin!
  if (event.origin !== "https://parent-site.com") {
    return; // Reject unknown senders
  }
  
  console.log("Received:", event.data);
});

The Security Critical Part

Origin checking is not automatic—developers must manually verify event.origin. Skipping this check is like opening mail from anyone without checking who sent it:

// DANGEROUS - accepts messages from ANY origin!
window.addEventListener("message", (event) => {
  eval(event.data); // Attacker-controlled code execution
});

Always specify the target origin when sending ("https://exact-domain.com", never "*") and always validate event.origin when receiving.

Key Takeaway: postMessage safely bridges the Same-Origin Policy gap, but security depends entirely on explicit origin checking—both when sending (target origin parameter) and receiving (validating event.origin).