DOM Access and Same-Origin Policy
You'll learn how the Same-Origin Policy prevents JavaScript in one origin from accessing or manipulating the DOM of documents from different origins, even when they share the same browser window.
The Core Protection Mechanism
The Same-Origin Policy (SOP) acts as a security boundary around the Document Object Model. When you have multiple frames, iframes, or windows open in a browser, JavaScript running in one document cannot freely access the DOM elements of another document unless they share the same origin (scheme, host, and port).
Think of it like apartment buildings with locked doors. Even though you can see your neighbor's apartment through the window, you can't walk in and rearrange their furniture. Similarly, a script from https://example.com can see that an iframe from https://bank.com exists, but it cannot read or modify the content inside that iframe.
What SOP Blocks
When origins don't match, JavaScript cannot:
- Read or modify DOM elements (
document.getElementById(),innerHTML, etc.) - Access form data or input values
- Read cookies or localStorage from the other origin
- Inspect styles or dimensions of elements
- Execute functions defined in the other document's context
What SOP Allows
Scripts can still perform limited cross-origin operations:
- Change the
locationof another window (navigation) - Post messages using
postMessage()API (controlled communication) - Access limited properties like
window.closedorwindow.length
This prevents malicious sites from embedding your bank's website in a hidden iframe and stealing your account information through DOM manipulation.
Key Takeaway: The Same-Origin Policy creates an impenetrable DOM barrier between different origins in the browser, preventing scripts from one site from reading or manipulating another site's page structure, protecting user data and preventing cross-site attacks.