Explain Codes LogoExplain Codes Logo

How do you use window.postMessage across domains?

javascript
cross-domain-communication
event-listeners
messageevent
Alex KataevbyAlex Kataev·Dec 19, 2024
TLDR

Cross-domain communication using window.postMessage requires sending a message and specifying a precise target origin. Here's a simple demo:

Sender (e.g., parent window):

// Setting up a listener for incoming gossip (messages) window.addEventListener('message', event => { if (event.origin !== "http://example.com") return; // Only believe messages from trusted origins // Process event.data, but first let's grab some chai ☕ });

Receiver (e.g., iframe):

// Here's the message with love ❤️ parent.postMessage("Hello, World!", "http://example.com");

For better security, validate origins vigilantly and target accurately.

Talk to parent from iframe

To talk to the parent page from an iframe, window.parent or window.top proves handy:

// Parent, do you hear me? 🎶 window.parent.postMessage("Message to parent", "http://parent-domain.com"); window.top.postMessage("Message to the top most superior window", "http://top-domain.com");

Always validate incoming messages to ensure security and prompt denial of threats.

Are we postMessage ready?

Always check if the user's browser is up to date to support window.postMessage functionality. Also, avoid using '*' as the targetOrigin. It's like inviting a stranger to dinner, no one does that! Always specify the receiving domain:

if (!window.postMessage) alert('Sorry, this disco club (browser) is outdated!');

Configure event listeners smartly, if outdated browser support is expected, window.attachEvent could be your saviour!

Subdomains and slashes

Subdomains are individual origins, much like cousins are separate individuals in a family. Slashes too are significant. They're like the period at the end of a sentence, a missing one can change meanings.

// Right window.postMessage('Hello', 'http://www.domain.com/'); // Wrong window.postMessage('Hello', 'http://www.domain.com'); // Trails off like a broken record...

Always review the URLs before starting your cross-domain chatter.

Visualize this!

Understanding window.postMessage and cross-domain communication is like deciphering the most riveting treasure hunt. Let's break it down:

Domain A (🏰): Sends a climatic **message** [📩] flaunting a legit wax seal (targetOrigin) Domain B (🌆): Only trusts letters with a familiar, trusted **wax seal**
window.postMessage('Shhhh... Secret message', 'https://domainB.com'); // 🏰 👉 🕊️ (carrying 📩) 👉 🌆 (aha, I know this seal, let's read 📩)

The talk about security during domains' chit-chat:

🏰: "I only trust messages with the seal of 🌆!" 🌆: "Wrong seal? Off to the furnace 🔥 it goes!"

Tips for secure conversation:

// 🏰 sends a message securely to 🌆, eluding the nosy neighbours (👤🕵️‍♂️👤) window.postMessage('Hello, secure domain B!', 'https://domainB.com'); // 📩🛡️

Deciphering MessageEvent

Understanding the MessageEvent object is critical. It's more than just "return to sender" postage:

window.addEventListener('message', event => { if (event.origin !== "http://example.com") return; console.log('Received top-secret data:', event.data); console.log('Sender domain:', event.origin); });

Analyse the event.origin and event.data in the message handler to avoid any unwanted surprises.

Test your might

Embed an iframe with the src attribute pointing towards your recipient domain. Always test your application across a range of browser versions.

<iframe src="http://example.com/iframe.html"></iframe> <!-- The more the tests, the merrier. -->