JavaScript's Same-Origin Policy Foundation
What you'll learn: How the browser's same-origin policy acts as a fundamental security boundary preventing JavaScript from one site accessing data from another.
The Core Concept
The Same-Origin Policy (SOP) is JavaScript's most important security mechanism. It's a rule enforced by browsers that prevents scripts from one origin (website) from accessing resources, windows, or iframes belonging to a different origin. An "origin" is defined by three components: protocol (http/https), domain (example.com), and port (80, 443, etc.). All three must match exactly for two resources to be same-origin.
Think of it like apartment building security: residents (scripts) can freely access their own apartment (origin), but cannot enter or look into their neighbor's apartment (different origin) without explicit permission.
Why This Matters
Without SOP, malicious JavaScript on evil.com could:
- Read your emails from
gmail.comif you're logged in - Access your banking information from
bank.com - Steal session tokens from any open tabs
The browser enforces SOP automatically, preventing scripts from:
- Reading content from cross-origin iframes
- Making AJAX requests to different origins (without CORS)
- Accessing cookies, localStorage, or DOM of other origins
- Manipulating windows or frames from different origins
Origin Matching Examples
https://example.com:443andhttps://example.com→ Same origin (443 is default HTTPS port)http://example.comandhttps://example.com→ Different (protocol differs)https://example.comandhttps://api.example.com→ Different (subdomain differs)https://example.com:443andhttps://example.com:8443→ Different (port differs)
Key Takeaway: The Same-Origin Policy creates strict boundaries between JavaScript code from different origins, preventing scripts from reading or manipulating resources across origin boundaries—this is the foundation of web browser security.