Same-origin policy

The same-origin policy is a browser rule that limits how a page or script from one origin can use a resource from another origin. It lets pages embed and link to other origins, but it stops them from reading the data.

Concept

Also called SOP

Updated

On this page

How it works

The browser compares the origin of the script with the origin of the resource. If the scheme, host, and port are not all equal, the script gets limited access. This stops a bad site from reading your webmail or your intranet pages with the visitor's cookies.

The rule has three parts. Cross-origin writes, such as links, redirects, and form posts, are usually allowed. Cross-origin embedding, such as images, scripts, and iframes, is usually allowed. Cross-origin reads are usually blocked.

In an iframe

A page can embed a frame from another origin. But each side gets only a small part of the other's Window. It can call postMessage, focus, blur, and close, and it can set location. It cannot read the DOM, cookies, or storage of the other page.

The same-origin policy does not stop framing. To stop other sites from framing your page, send Content-Security-Policy: frame-ancestors or X-Frame-Options. To let two origins share data on purpose, use postMessage between windows or CORS for HTTP requests.

Example

JavaScript on https://example.com
const frame = document.querySelector("iframe"); // src="https://widget.example"

frame.contentWindow.postMessage("hello", "https://widget.example"); // allowed
frame.contentWindow.document; // blocked: throws a SecurityError

A page can send messages to a cross-origin frame, but it cannot read the frame's document.

Learn more

Sources

Know before you embed.

Free, no sign-up, nothing stored. Paste a URL and get a verdict, a live preview, and the fix.