Description
With targetOrigin set to '*', window.postMessage delivers to the window you reference regardless of its current origin. If that window or iframe navigates to an untrusted site, the new page may receive the token or personal data you send.
Potential impact
An unintended recipient may receive session data, authentication tokens or OAuth codes and misuse the user’s API access. Payment or settings messages may also reach the wrong page.
Remediation
- Set
targetOriginfrom trusted configuration using the exact scheme, host and port. For multiple destinations, choose from an allow-list and skip sending if none matches. Never rely on a user-controllediframe.src. - Send only the data the receiver needs. If a one-time token is necessary, restrict its purpose, recipient and lifetime. At the receiver, check
event.origin,event.source, the message type and its fields. - Set the iframe destination to a trusted URL and apply suitable sandbox restrictions. For new windows that do not need opener communication, use
noopener.
Examples
Before
// sender (parent page)
const iframe = document.getElementById("payFrame");
// Send the locally stored authentication token (confidential data)
const token = localStorage.getItem("auth_jwt");
// Using '*' lets the target receive the message at any origin
iframe.contentWindow.postMessage({ type: "AUTH", token }, "*");
After
// sender (parent page)
const iframe = document.getElementById("payFrame");
// Fix the target origin in trusted configuration
const TARGET_ORIGIN = "https://pay.example.com";
// Avoid confidential data or minimize it, for example with a one-time code
const message = { type: "REQUEST_PAYMENT", orderId: "ORD-2025-0912-001" };
iframe.contentWindow.postMessage(message, TARGET_ORIGIN);
// receiver (child iframe page)
window.addEventListener("message", (event) => {
// Accept only the expected parent origin
if (event.origin !== "https://app.example.com") return;
if (event.source !== window.parent) return;
// Validate the message shape and type
if (!event.data || event.data.type !== "REQUEST_PAYMENT") return;
if (typeof event.data.orderId !== "string") return;
// Separately verify order access and payment conditions on the server
processPayment(event.data.orderId);
});
The parent sends an order ID only to https://pay.example.com. On the separate iframe page, the receiver checks the parent origin and window, message type and order ID type. The omitted processPayment implementation must verify order access and payment conditions on the server.