Course contentsShow
← Security
Lesson 1047 of 3,05222. Web Security - Client-Side and SPA SecurityFree lesson

JavaScript's Same-Origin Policy Foundation

Explore the core same-origin restrictions that govern JavaScript access to resources, windows, and iframes across origins.

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.com if 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:443 and https://example.com → Same origin (443 is default HTTPS port)
  • http://example.com and https://example.com → Different (protocol differs)
  • https://example.com and https://api.example.com → Different (subdomain differs)
  • https://example.com:443 and https://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.