The same-origin policy
An overview,
meaning
“Homology” refers to:
- The protocols must be the same
- The domain name must be the same
- Ports must be the same
purpose
The same-origin policy protects user information from malicious websites
limits
Three kinds of behaviorBe restricted:
- An ajax request
- Dom not available
- Cookie, localStorage, and indexDB cannot be read
Second, the Cookie
cookie
Is a small piece of information written by the browser that can only be shared by web pages of the same origin. The size limit is 4K.
If the first level domain name of two pages is the same and the second level domain name is different, you can share cookies by setting the same document.domain.
document.domain = "example.com"Copy the code
Cookies and iframe
.localStorage
andindexDB
It is not suitable to circumvent the same origin policy in this waypostMessage api
.
The server can also set the domain field as a level 1 domain name when setting cookies.
Set-Cookie: key=value; domain=.example.com; path=/Copy the code
Third, iframe
Two pages with different domain namesI can’t get
DOM
The classic example isiframe
Window andwindow.open
Open window. They cannot communicate with the parent window.
For example, if the parent window runs the command, an error will be reported if the iframe is not of the same origin.
document.getElementById("myIFrame").contentWindow.document
// Uncaught DOMException: Blocked a frame from accessing a cross-origin frame.Copy the code
contentWindow
Yes return currentiframe
The object’swindow
Object, which can be passedwindow
Object accessiframe
Internal documentation anddom
The reverse is also true if the child window gets the PARENT window’s DOM.
Solutions:
document.domain
Property, circumvent the same origin policy, getdom
.
Completely different source pages, there are three ways:
- Fragment Identifier
- window.name
- Cross-document communication API
Fragment identifier, which refers to the hash part of the link URL
For example: “https://www.example.com/blog/2016/04/same-origin-policy.html#name=1” name = 1
Part, only the hash part is changed, the page is not refreshed.
hash
Partial changes while the page does not refresh.let src = originUrl + The '#' + data
document.getElementById("myIFrame").src = srcwindow.onhashchange = () => {
console.log(location.hash)
}Copy the code
Similarly, the child window can set the hash portion of the parent window.
parent.location.href = target + The '#' + dataCopy the code
Window.name refers to the name property of the current window. A window corresponds to a name property, that is, when opened
A new window has nothing to do with the name property of the previous window.
// Set attribute window.name = data // get attribute console.log(document.getelementByid ("myIFrame").contentWindow.name)Copy the code
Cross-document Messaging API
var data = window.open('https://example2.com'.'title')
data.postMessage('hello'.'https://example2.com')Copy the code
If yes, https://www.example.com, that is, protocol + domain name + port, can also be set to *
message
Event to listen for messages from the other party.
window.addEventListener('message', (e) => {
console.log(e.data)
})
Copy the code
e
, has three attributes:
- E.ource: window for sending messages
- E.olin: Window to receive messages
- E. data: Message content
Using window.postMessage, you can also read and write LocalStorage from other Windows.
Four, AJAX
- JSONP
- CORS
- WebSocket
The biggest feature is: compatible with the old browser, server transformation is small. Only GET requests can be processed.
JSONP
The principle is to use<script>
Tags have no cross-domain limitation vulnerabilities. through<script>
The tag points to an address that needs to be accessed and provides a callback function to receive data. or<img>
The label
Key points:
- The data returned by the server is not
JSON
, butJavaScript
That is to saycontentType
istext/javascript
, the content format iscallbackFunction(JSON)
callbackFunction
You need to registerwindow
Object, becausescript
The execution scope after loading iswindow
scope- You need to think about multiple at the same time
JSONP
The condition of the request,callbackFunction
Hang onwindow
The attribute name on the - End Indicates the request that needs to be removed
script
The labels andwindow
The callback function on
jsonp({
url: ' ',
data: {
key: 'value'
},
callback: (data) => {
console.log(data)
}
})Copy the code
functionThe json ({url, data, the callback}) {/ / get the head tag const container = document. The getElementsByTagName ('head') [0]; // Dynamically generates the callback function name const cbName = 'jsonp_${new Date().getTime()}// Create a script tag const dom = document.createElement('script'// Set the SRC attribute of the script tag script.src = '${url}?${objectToQuery(data)}&callback=${cbName}`
script.type = 'text/javascript'AppendChild (dom) registers the callback function window[cnName] = on windowfunctionContainer.removechild (dom) delete window[cbName]} dom.onError = () => { window[cnName] = () => { callback && callback('some error'Container. RemoveChild (dom) delete window[cbName]}}} // Concatenate parametersfunction objectToQuery (obj) {
const arr = [];
for ( var i in o) {
arr.push(encodeURIComponent(i)+ '=' +encodeURIComponent(o[i]));
}
return arr.join('&');
}Copy the code
Is a communication protocol that uses ws:// and WSS :// as prefixes because this protocol does not enforce the same origin policy and can communicate across sources as long as the server supports it.
GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
Origin: http://example.com
Copy the code
Cross-Origin-ResourceSharing
Cross-domain resource sharing. The ultimate solution for cross-domain requests.- The whole communication process is done automatically by the browser.
- Once the browser finds out
AJAX
When the request crosses domains, it willAutomatically addSome additional headers, and sometimes an additional request. - As long as the server supports it
CORS
, you can cross domains
Browsers classify CORS requests into simple requests and non-simple requests
- The request method is one of the following three:
- get
- post
- head
- The header information does not exceed the following fields:
- Accept
- Accept-Language
- Content-Language
- Last-Event-ID
- Content-type: Only three values: Application/X-www-form-urlencoded, multipart/form-data, text/plain
As long as the above conditions are not met, the request is not simple.
- The browser detects that the request is simple and automatically adds the Origin field in the header information
- Server based on
origin
Field to determine whether the request is approved or not - To the extent permitted, several headers are added to the response header.
-
Access-Control-Allow-Origin: http://api.bob.com Access-Control-Allow-Credentials: true Access-Control-Expose-Headers: FooBar Content-Type: text/html; charset=utf-8Copy the code
- Not within the permitted range, return a normal
HTTP
In response to - The browser determines if there is any in the response header
Access-Control-Allow-Origin
Field, error if no,beXMLHttpRequest
的onerror
Callback function capture. This type of error is not recognized by the status code becauseHTTP
The status code of the response may be200
Access-control-allow-origin: This field is required to either be the value of the requested Origin field or * to indicate that Access is allowed by any domain name.
CORS requests do not send cookies and HTTP authentication information by default.
Cookies are sent to the serverOn the one hand, the server agrees to specify
Access-Control-Allow-Credentials
Field.
Access - Control - Allow - Credentials:trueCopy the code
withCredentials
attribute
let xhr = new XMLHttpRequest();
xhr.withCredentials = trueCopy the code
Access-Control-Allow-Origin
The domain name must be the same as the source of the request.
Common cases: The request method is PUT or DELETE, or the content-type field is Application/JSON.
- Non-simple requests are being sent
cors
The request is sent once before it is requestedOPTIONS
Request, calledPrecheck request. - The browser first asks the server if the requested domain name is in the whitelist and what is available
HTTP
Verb and header information fields - The browser will only issue a formal response if it receives a positive response
XMLHttpReques
T request
Origin: indicates the request source
Access-control-request-method: This field is required and represents the Request Method
- After receiving the precheck request, the server checks the above three fields to confirm that cross-source requests are allowed and responds
- If the cross-source request is denied, the server returns a normal
HTTP
But there is no correlationCORS
The response header field of. The browser throws an error,beThe XMLHttpRequest onerror
Callback function capture - If a cross-source request is agreed, the server adds some fields to the request header
Access-control-allow-methods: GET, POST, PUT. This field is required to represent all requested methods supported by the server
Access-Control-Request-Headers
Field, which must also be present in the response header, representing all header information fields supported by the server
Access-control-allow-credentials: This field is optional and indicates whether cookies are allowed to be sent. Cookies are not included in cORS requests by default
JSONP
Only supportget
Request, but compatible with older browsersCORS
All requests are supported, but not compatibleie10
The following
Cross-domain resource Sharing CORS
www.ruanyifeng.com/blog/2016/0…)
How to achieve a high quality JSONP (
Juejin. Cn/post / 684490…)
Browser Same-origin policy and its Circumvention method (
www.ruanyifeng.com/blog/2016/0…)