QA
Senior LevelHTML & Semantic Web

How do you implement secure cross-origin window communication via window.postMessage()?

❓ Interview Prompt: Explain window.postMessage(), targetOrigin validation, origin checking inside message listeners, and preventing data leakage.

Communicating between parent windows and cross-origin iframes requires 'window.postMessage()'.

Security Checklist:

1
Specify Target Origin: Never pass '*' as 'targetOrigin' when sending sensitive data! Specify exact target domain ('https://trusted-iframe.com').
2
Validate Origin: In the message event listener, ALWAYS check 'event.origin === "https://expected-domain.com"' before processing payload!

Code Implementation Example

javascript
// Parent sending message to iframe
iframeWindow.postMessage({ token: 'abc123' }, 'https://trusted-iframe.com');

// Receiver validating origin
window.addEventListener('message', (event) => {
  if (event.origin !== 'https://trusted-iframe.com') return; // Reject unauthorized origin!
  console.log('Received payload:', event.data);
});
💡Secure postMessage communication with explicit targetOrigin and origin validation.
🎯 Interview Key Takeaway

Always specify exact targetOrigin when calling postMessage(), and validate event.origin inside message event listeners.

#postMessage#Cross-Origin#iframe Security#Senior
Back to all HTML & Semantic Web Questions→

More HTML & Semantic Web Interview Questions

Beginner LevelHTML & Semantic Web

What is Semantic HTML and why is it essential for modern web applications?

Beginner LevelHTML & Semantic Web

What is <!DOCTYPE html> and what happens if it is omitted?

Beginner LevelHTML & Semantic Web

What is the difference between inline and block-level HTML elements?