Skip to main content

index

postMessage() Vulnerabilities

What is postMessage()

window.postMessage() is a JavaScript API enabling secure, controlled communication between different browser windows/frames (origins), solving the Same-Origin Policy (SOP) blockade that prevents direct data exchange, vital for features like OAuth popups, embedded widgets, and cross-domain iframes, allowing one window to send data to another without granting full access.

Problem it tries to solve

Browsers enforce the Same-Origin Policy (SOP):

  • A page from site-A.com cannot directly read data from site-B.com
  • This breaks legitimate use-cases like:
    • OAuth popups
    • Embedded iframes
    • Cross-domain widgets

postMessage() exists to safely exchange messages across origins.

How postMessage() works

Basic syntax:

targetWindow.postMessage(message, targetOrigin)

Example:

window.opener.postMessage(
{ token: "secret" },
"https://example.com"
)

Key parts:

  • message → Data being sent
  • targetOrigin → Who is allowed to receive it

Receiving messages

A page listens using:

window.addEventListener("message", function(event) {
console.log(event.data);
});

Important properties:

  • event.data → message content
  • event.origin → sender’s origin
  • event.source → sender window