Same‑Origin Policy and Cross‑Origin Techniques in Web Development
This article explains the fundamentals of the browser same‑origin policy, defines what constitutes an origin, describes the restrictions it imposes, and surveys practical cross‑origin solutions such as dynamic tags, JSONP, CORS, postMessage, document.domain, window.name, fetch, and WebSocket.
1. Same‑Origin and Cross‑Domain
In most cases a domain is prohibited from reading data from another domain, but it may load resources such as scripts, images, and styles from external origins, and embed external pages via <iframe> or <frame> . Selective cross‑origin reads are possible through Cross‑Origin Resource Sharing (CORS), which grants access on a per‑origin basis.
1.1 Basics
The same‑origin policy (SOP) restricts messages from one origin to another. It permits GET and POST HTTP requests across origins while blocking PUT and DELETE, and disallows custom request headers when contacting a different origin. The browser, not the server, enforces these rules.
1.2 What Is an Origin?
RFC6454 defines an origin as the triple (scheme, host, port) extracted from a resource's URI. For example, the origin of https://www.test.com/test-script.js is (https, www.test.com, 80). A script inherits the origin of the resource that loaded it; relative URLs and schemes without a clear origin (e.g., javascript: , data: ) adopt the page's origin.
Internet Explorer historically omitted the port from the origin calculation, causing compatibility quirks that persisted through IE8‑11.
1.3 When Are Two Resources Same‑Origin?
Two resources are same‑origin only when their scheme, host, and port are identical. Different schemes (http vs https) or different hostnames (www.testA.com vs www.testB.com) constitute different origins.
1.4 Same‑Origin Policy Rules
The SOP isolates resources from different origins to improve security. Its rules can be grouped into three levels:
a. No Restrictions
Execute scripts from other domains (e.g., CDN scripts, JSONP).
Render images from other domains ( <img> ).
Apply stylesheets from other domains ( <link> ).
Embed resources via <iframe> or <frame> .
Redirect pages using <a> links.
Submit data with <form> to other origins.
Share sub‑domain resources by setting document.domain .
Use window.name for data transfer.
Access ancestor windows via parent.parent… .
Communicate with postMessage .
Load media and fonts from other origins ( <video> , <audio> , <object> , <embed> , <applet> , @font-face ).
b. Partial Restrictions
Cross‑origin requests cannot set custom HTTP headers.
Only GET and POST are allowed; PUT and DELETE are blocked.
Scripts can access the top‑level window of another origin but not its internal DOM.
CORS can relax some restrictions, but credentials (cookies, tokens) are omitted unless withCredentials=true and the server permits them.
c. Full Restrictions
Local file system read/write is blocked.
Cookie access is restricted.
FileUpload value cannot be read or modified.
Scripts cannot read/write documents from different servers.
Access to localStorage , sessionStorage , and IndexedDB is limited.
XMLHttpRequest objects are constrained.
1.5 Cross‑Domain Communication
While SOP isolates origins, legitimate cross‑origin interactions are needed for scenarios such as iframe resizing, single sign‑on, and server‑to‑server authentication. Various techniques exist to achieve this safely.
2. Cross‑Domain Methods Overview
Methods can either bypass the browser's SOP or leverage its allowed interfaces.
2.1 Avoid the Problem
Deploy the web application under a single domain or use a backend proxy to forward cross‑origin requests.
2.2 Reverse Proxy
Configure Apache, Nginx, etc., to proxy external requests through the same origin.
2.3 Direct Techniques
2.3.1 Dynamic Tags
Insert tags such as <script> , <img> , <link> , <iframe> , <frame> dynamically; the browser loads them without SOP checks.
2.3.2 JSONP
Leverages the unrestricted loading of <script> tags. The server returns a JavaScript call like callback({"data":[{"aa":1}]}) , which executes with the data as an argument.
2.3.3 Form Submission
Forms can submit data via GET or POST to any origin without SOP constraints.
2.3.4 document.domain
Sub‑domains can set a common parent domain (e.g., test.com ) to enable direct access between them.
2.3.5 window.name
The window.name property persists across page loads and can be used as a shared storage channel.
2.3.6 CORS
Servers declare allowed origins via Access-Control-Allow-Origin and may permit credentials with Access-Control-Allow-Credentials:true . Browsers send cross‑origin requests without credentials unless withCredentials=true .
2.3.7 postMessage
HTML5 API for safe, asynchronous communication between windows/iframes across origins.
2.4 Fetch API
2.4.1 With Credentials
Request: credentials:true
Response headers: Access-Control-Allow-Origin:http://origin.to.cross , Access-Control-Allow-Credentials:true
2.4.2 Request Options
mode : same-origin , cors , no-cors (default), navigate , websocket
credentials : omit (default), same-origin , include
2.4.3 Response Types
Same‑origin: basic , cors , default , error
Cross‑origin: opaque , opaqueredirect , error
2.4.4 WebSocket
HTML5 full‑duplex communication channel that is not subject to SOP, useful for real‑time cross‑origin data transfer (note: secure pages cannot open ws:// connections).
3. Different Perspectives
3.1 Local Page‑to‑Page vs. Browser‑Server Communication
3.1.1 Local Page‑to‑Page
Dynamic tags
postMessage
window.name
document.domain
3.1.2 Browser‑Server
GET: dynamic tags, JSONP, Form, CORS, WebSocket, fetch
POST: Form, CORS, WebSocket, fetch
3.2 Unidirectional vs. Bidirectional Communication
Unidirectional
Dynamic tags, JSONP, Form, CORS, fetch
Bidirectional
window.name, document.domain, postMessage, WebSocket
3.3 Front‑End Only vs. Backend‑Assisted
Front‑End Only
Dynamic tags, window.name, document.domain, postMessage, fetch
Backend‑Assisted
JSONP, Form, CORS, WebSocket
3.4 Legacy vs. Modern Browsers
Legacy Browsers
Dynamic tags, JSONP, Form, window.name, document.domain
Modern Browsers
All of the above plus CORS, postMessage, WebSocket, fetch
References
RFC 6454 – The Web Origin Concept ( https://tools.ietf.org/html/rfc6454 )
W3C Same‑Origin Policy ( https://www.w3.org/Security/wiki/Same_Origin_Policy )
MDN – CORS ( https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS )
《Web之困‑现代Web应用安全指南》
Qunar Tech Salon
Qunar Tech Salon is a learning and exchange platform for Qunar engineers and industry peers. We share cutting-edge technology trends and topics, providing a free platform for mid-to-senior technical professionals to exchange and learn.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.