JavaScriptHard
What is the Same-Origin Policy?
The Same-Origin Policy (SOP) is the browser's core security rule that a page can freely interact only with resources from the same origin (same scheme, host and port); reading data from other origins is blocked unless they opt in, for example with CORS.
What counts as the same origin
Scheme + host + port must all match.
https://app.example.comvshttps://app.example.com/page: same origin.- vs
http://app.example.com: different scheme. - vs
https://api.example.com: different host (subdomains count). - vs
https://app.example.com:8443: different port.
What SOP restricts
- Reading cross-origin responses from
fetch/XHR (unless CORS allows it). - Accessing the DOM of a cross-origin iframe or popup (
iframe.contentWindow.document). - Reading cross-origin storage:
localStorage, IndexedDB and cookies are scoped to their own origin (cookies use slightly different "site" rules). - Reading pixels from a cross-origin image drawn on a canvas (the canvas becomes "tainted").
What SOP allows
- Embedding:
<img>,<script>,<link rel="stylesheet">,<video>,<iframe>can load from anywhere. - Sending requests (form posts, navigation). This is why CSRF is possible and why
SameSitecookies and CSRF tokens exist.
Controlled ways to cross origins
- CORS for HTTP APIs.
postMessagefor communication between windows and iframes (always checkevent.origin).- A proxy/BFF on your own origin that calls the other service server-side.
Why it matters
Without SOP, any site you visit could read your email or bank data using your logged-in cookies.
Code example
js
1// Compare origins with the URL API2const sameOrigin = (a, b) => new URL(a).origin === new URL(b).origin;34const page = "https://app.example.com/dashboard";5console.log(sameOrigin(page, "https://app.example.com/settings")); // true6console.log(sameOrigin(page, "http://app.example.com")); // false - scheme7console.log(sameOrigin(page, "https://api.example.com")); // false - host8console.log(sameOrigin(page, "https://app.example.com:8443")); // false - port910// Safe cross-origin messaging with postMessage11const TRUSTED = "https://widgets.example.com";12window.addEventListener("message", (event) => {13 if (event.origin !== TRUSTED) return; // always check who sent it14 console.log("trusted message:", event.data);15});16// The parent page sends with an explicit target origin, never "*":17// iframe.contentWindow.postMessage({ type: "theme", value: "dark" }, TRUSTED);1819// Reading a cross-origin response without CORS fails in the browser20try {21 await fetch("https://example.com/", { signal: AbortSignal.timeout(3000) }); // no CORS headers22 console.log("allowed (the server sent CORS headers)");23} catch (e) {24 console.log("blocked or offline:", e.name); // TypeError - the browser refused to expose the response25}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.