SOP Impact on JavaScript and DOM Access
You'll learn how the Same-Origin Policy physically prevents JavaScript from one origin from reaching into and manipulating the DOM or properties of windows/frames from another origin.
What It Actually Blocks
The Same-Origin Policy doesn't just exist in theory—it actively prevents cross-origin JavaScript from reading or modifying content. When a page from https://bank.com embeds an iframe from https://evil.com, the browser enforces a strict barrier:
- Evil.com's JavaScript cannot read the DOM tree of bank.com's parent window
- Evil.com cannot access
window.parent.documentor any properties/methods that would reveal bank.com's content - Evil.com cannot read cookies, localStorage, or sessionStorage belonging to bank.com
- Bank.com cannot reach into evil.com's iframe to read its contents either
Why This Matters
Imagine a malicious site embedding your banking page in a hidden iframe. Without SOP, the malicious JavaScript could:
// ❌ BLOCKED by SOP — throws SecurityError
const stolenBalance = window.frames[0].document.querySelector('.balance').textContent;
const stolenToken = window.frames[0].localStorage.getItem('auth-token');
The browser throws a SecurityError when cross-origin scripts attempt DOM access. This is intentional and protective.
The Window Reference Loophole
Interestingly, you can get a reference to a cross-origin window object (like window.parent or window.opener), but you cannot read its useful properties. You can call very limited methods like postMessage() or navigate it using location.href (write-only), but reading is blocked.
Key Takeaway: Same-Origin Policy enforces a hard barrier preventing cross-origin JavaScript from reading DOM content, accessing storage, or inspecting properties of windows/frames from different origins—this is the browser's fundamental defense against malicious data theft.