When establishing HTML
rules, for security reasons, a website from one origin is not allowed to interact with resources from another origin, and the browser sets this rule as the same-origin policy.
The same origin refers to websites having the same domain, that is, the protocol, host, and port are the same.
Embedding cross-origin resources is allowed, but the browser restricts JavaScript
from interacting with the loaded content, such as embedded <script>
, <img>
, <link>
, <iframe>
, among others.
XHR
requests cannot be sent.Cookie
and LocalStorage
from different origins cannot be accessed.Since <script>
can request cross-origin resources, a callback
function name can be appended dynamically to a <script>
tag using the DOM
, which will be called upon completion of the request.
For simple requests, the browser will directly send a CORS
request by adding the Origin
request header in the header. Likewise, in the response header, the server will return the relevant CORS
header fields it has set, with the Access-Control-Allow-Origin
field allowing the source to make cross-origin requests. When sending the request, the browser will specify the requesting source in the Origin
request header, and if the server allows cross-origin requests from that source, it will return successfully.
For non-simple requests, the browser will first automatically send an OPTIONS
request. If the server supports the request, it will send the actual request to the backend. Otherwise, if the server does not support the request, an error will be logged in the console.
By using proxy, listening on the same port, and adding different paths, cross-origin access between different services can be achieved.
Simply create a new <img>
and include some basic data in the address. This method only supports get
requests and can only send requests to the server unilaterally, which is commonly used for tracking ad impressions and is also frequently employed in XSS
attacks to obtain cookies
.
document.domain
For example, for www.example.com
and abc.example.com
, their primary domain is the same.
window.name
Different domain iframes store shared information in window.name
, this method only applies to cross-origin communication between two iframes.
window.postMessage
Use window.postMessage
to send messages to other window
objects, regardless of whether the window
object belongs to the same origin or a different origin. This method cannot be used to exchange data with the server.