Cross-Window Communication in JavaScript
🔐 Understanding the Same-Origin Policy
Cross-Window Communication in JavaScript
🔐 Understanding the Same-Origin Policy
Before we dive into cross-window communication, we need to understand the Same-Origin Policy (SOP), a critical security feature in browsers.

What is the Same-Origin Policy?
Two URLs are considered to have the same origin if they share:
- The same protocol (
httpvshttps) - The same domain (
example.comvssub.example.com) - The same port (default is
80forhttpand443forhttps)
✅ Same Origin Examples:
http://example.com
http://example.com/page.html
http://example.com:80/dashboard
❌ Different Origin Examples:
https://example.com (different protocol)
http://www.example.com (different subdomain)
http://example.org (different domain)
http://example.com:8080 (different port)
Why Does SOP Exist?
Imagine you have two tabs open:
john-smith.com(malicious site)gmail.com(your email)
Without SOP, JavaScript from john-smith.com could read your emails from gmail.com! SOP prevents this by restricting cross-origin access.
🖼️ iframes and Cross-Window Access
An <iframe> embeds another document inside your page. You can access its content only if it follows the Same-Origin Policy.
Accessing an iframe’s Content
<iframe src="https://example.com" id="myFrame"></iframe>
<script>
const iframe = document.getElementById('myFrame');
iframe.onload = function() {
// ✅ Accessing the window inside the iframe
const iframeWindow = iframe.contentWindow;
// ❌ Trying to access the document (fails if cross-origin)
try {
const doc = iframe.contentDocument; // Throws SecurityError
} catch (e) {
console.error("Blocked by Same-Origin Policy!");
}
// ❌ Reading iframe.location.href (also blocked)
try {
const href = iframe.contentWindow.location.href; // SecurityError
} catch (e) {
console.error("Cannot read iframe URL!");
}
// ✅ But we CAN change the iframe's location!
iframe.contentWindow.location = "https://google.com"; // Works!
};
</script>
Same-Origin iframe (Full Access)
If the iframe is from the same origin, you can manipulate its DOM freely:
<iframe src="/same-origin-page.html" id="safeFrame"></iframe>
<script>
const safeFrame = document.getElementById('safeFrame');
safeFrame.onload = function() {
// ✅ Full access to the iframe's document
safeFrame.contentDocument.body.innerHTML = "<h1>Hello from parent!</h1>";
};
</script>
📨 Cross-Origin Communication with postMessage
Since SOP blocks direct access, we use postMessage for secure cross-window communication.
Sending a Message (postMessage)
// Parent window sending a message to an iframe
const iframe = document.getElementById('myFrame');
iframe.contentWindow.postMessage("Hello from parent!", "https://example.com");
- First arg: The message (can be an object, string, etc.).
- Second arg: The target origin (
"https://example.com"or"*"for any origin).
Receiving a Message (message event)
// Inside the iframe (or another window)
window.addEventListener("message", (event) => {
// ✅ Check the sender’s origin for security
if (event.origin !== "https://parent-site.com") return;
console.log("Received:", event.data); // "Hello from parent!"
// ✅ Reply back to the sender
event.source.postMessage("Hello back!", event.origin);
});
Full Example: Parent ↔ iframe Communication
Parent Window (parent.html):
<iframe src="child.html" id="childFrame"></iframe>
<script>
const childFrame = document.getElementById('childFrame');
childFrame.onload = function() {
childFrame.contentWindow.postMessage("Hello, child!", "*");
};
// Listen for replies
window.addEventListener("message", (event) => {
if (event.origin !== "http://child-site.com") return;
console.log("Child says:", event.data); // "Hi, parent!"
});
</script>
Child Window (child.html):
<script>
window.addEventListener("message", (event) => {
if (event.origin !== "http://parent-site.com") return;
console.log("Parent says:", event.data); // "Hello, child!"
event.source.postMessage("Hi, parent!", event.origin);
});
</script>
🔧 Advanced Techniques
1. Using document.domain for Subdomains
If two windows are on subdomains (a.example.com and b.example.com), you can relax SOP by setting:
// In both windows:
document.domain = "example.com";
Now they can interact as if they were same-origin.
⚠️ Deprecated but still works (modern alternative: postMessage).
2. Sandboxing iframes
The sandbox attribute restricts iframe capabilities:
<iframe sandbox="allow-scripts allow-forms" src="untrusted.html"></iframe>
- Blocks access to parent DOM.
- Disables scripts unless
allow-scriptsis set.
3. Detecting iframe Readiness
Since iframe.onload fires only after full load, use setInterval for early detection:
const iframe = document.getElementById('myFrame');
const timer = setInterval(() => {
if (iframe.contentDocument) {
clearInterval(timer);
console.log("iframe document is ready!");
}
}, 100);
📜 Summary
| 📜 Summary Method | Use Case | Security Consideration |
|---|---|---|
| iframe.contentWindow | Access same-origin iframes | SOP enforced |
| postMessage | Cross-origin communication | Always verify event.origin |
| document.domain | Subdomain relaxation | Deprecated, avoid in new code |
| sandbox | Secure untrusted iframes | Restricts scripts/forms |
Final Thoughts
Cross-window communication is powerful but must be handled securely. Always:
✔ Use postMessage for cross-origin communication.
✔ Verify event.origin to prevent attacks.
✔ Prefer sandbox for untrusted iframes.
Thank you for being a part of the community
Before you go:
- Be sure to clap and follow the writer ️👏️️
- Follow us: **X | [LinkedIn](https://www.linkedin.com/company/inplainenglish/) | [YouTube](https://www.youtube.com/@InPlainEnglish) | [Newsletter](https://newsletter.plainenglish.io/) | [Podcast](https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0) | [Twitch](https://twitch.tv/inplainenglish)**
- **Start your own free AI-powered blog on Differ** 🚀
- **Join our content creators community on Discord** 🧑🏻💻
- For more content, visit **plainenglish.io + [stackademic.com](https://stackademic.com/)**
메타데이터
- post_id
- bcf4fe814666
- slug
- cross-window-communication-in-javascript-bcf4fe814666
- url
- https://javascript.plainenglish.io/cross-window-communication-in-javascript-bcf4fe814666
- canonical_url
- https://javascript.plainenglish.io/cross-window-communication-in-javascript-bcf4fe814666
- author_url
- https://medium.com/@akshatmtiwari
- status
- ok
- fetched_at
- 2026-07-24 17:38:50