EMZETT.
Login

Same-origin policy: Why browsers wall off foreign data

In short: The same-origin policy only allows scripts of a page to access data of the same origin (protocol, host, port); it protects users from malicious pages.

In more detail: You are logged in at a bank and open a foreign page in another tab. Without protection its JavaScript could fetch data from your bank account. The same-origin policy (SOP) is the browsers’ basic security rule against this.

In Depth

What is an origin?

An origin consists of protocol + host + port:

  • https://example.com and https://example.com/page → same.
  • http://example.com → different (protocol).
  • https://api.example.com → different (host).
  • https://example.com:8443 → different (port). Only with the same origin may JavaScript read the responses and access the DOM.

What the SOP prevents and what not

Blocked: reading responses via fetch/XHR to foreign origins, access to the DOM of foreign iframes, reading foreign cookies via JavaScript. Allowed: embedding (not reading) images, scripts, styles, iframes, sending forms and links. That is why further protections are needed against CSRF (requests with your cookies from foreign pages) and XSS (foreign code on your own page that runs within the origin and bypasses the SOP).

Relaxations

  • CORS: the server explicitly allows certain origins access (header Access-Control-Allow-Origin).
  • postMessage: controlled message exchange between windows/iframes.
  • document.domain (deprecated) and JSONP (deprecated, dangerous).
  • Cookie attributes SameSite, HttpOnly, Secure complement the protection.

Practice

You cannot simply fetch foreign data in the browser; build your own server/proxy instead or enable CORS on the server. Include only trustworthy scripts, use Content Security Policy, subresource integrity and isolation (Cross-Origin-Opener-Policy). The SOP protects users, not servers: additionally protect interfaces with authentication and authorisation.

See also: CORS, CSRF, XSS, CORS error