What is cross-domain

If one of the three is different, the two pages are from different sources. Pages from different sources can have cross-domain problems.

If they are not homologous, the following three are restricted

(1) Cookies, LocalStorage, and IndexDB cannot be read.

(2) DOM cannot be obtained.

(3) The AJAX request cannot be sent.

Cross-domain types and solutions

Cross domains with the same primary domain

If the primary domain names of the two pages are the same, for example, static.a.com and info.a.com, you can set the document.domain of both pages to a.com to pass the homologous test.

(1) In www.a.com/a.html:

document.domain = 'a.com';
var ifr = document.createElement('iframe');
ifr.src =  'http://www.script.a.com/b.html';  
ifr.display = none;
document.body.appendChild(ifr);
ifr.onload = function(){ 
    var doc = ifr.contentDocument 
 ifr.contentWindow.document;                                           
    ifr.onload = null;
};
Copy the code

(2) In www.script.a.com/b.html:

document.domain = 'a.com';
// Note: When using document.domain to allow subdomains to securely access their parent domain, you need to set the document domain to have the same value in both parent and subdomains. This is necessary even if doing so only sets the parent field back to its original value. Otherwise, permission errors may occur. Here are all a.com.
Copy the code

Cross-domain of completely different sources (communication between two pages)

Cross domains using location.hash

C1.html under a.com and c2.html under jianshu.com create a hidden iframe with SRC pointing to c2.html

2. C2.html Responds to the request and changes the hash value of C1.html

C1.html adds a timer to listen for changes in location.hash

Advantages: 1. It can solve the cross-domain problem where domain names are completely different. 2. Two-way communication can be realized.

Disadvantages: Location. hash is directly exposed to the URL and will generate historical records in some browsers. Low data security also affects user experience. In addition, due to the URL size limit, the amount of data that can be passed is not large. Some browsers do not support the OnHashChange event and require polling to learn about URL changes.

Cross domains by window.name

The window object has a name property that has one characteristic: That is, during the life cycle of a window, all pages loaded in the window share a window.name, and each page has read and write permissions to window.name, which persists in all pages loaded in a window. The magic of the window.name property is that the name value persists after different pages (or even different domain names) have been loaded (it doesn’t change if you don’t change it), and very long name values (2MB) can be supported.

 window.name = data;// The parent window opens a child window to load a web page from a different source, which writes the information.

 location = 'http://parent.url.com/xxx.html';// Next, the child window jumps back to a url in the same domain as the main window.

 var data = document.getElementById('myFrame'). ContentWindow. Name.// Then, the main window can read the child window window.name.
Copy the code

If you are communicating with an iframe, you need to set the SRC of the iframe to a page address in the current domain.

so

Open c2.html under jianshu.com under iframe

2. Set window.name in c1.html, and all pages opened by him can get and change window.name

Cross domains via window.postMessage

The inside page of an iframe sends a message to the outside.

/ / in the iframe
window.parent.postMessage({aa: 123}, 'http://static.synapse.xin');

// Parent page
window.addEventListener('message'.function(e){
    console.log(e);
})
Copy the code

Aaa.com opens bbb.com and sends a message to BBB

The parent page opens the child page and sends a message. The child page receives and replies to the message.

// Parent page
var popup = window.open('http://bbb.com'.'title');
popup.postMessage({aa: 123}, 'http://bbb.com');

// Child page
function onmessage(e) {
    console.log(e);
    // e.ata sends data {aa: 123}
    // e.rigin The address of the source http://aaa.com
    // e.ource The window object of the message source
    if(e.origin == 'http://aaa.com'){
        e.source.postMessage('nice to see you'.The '*')}}if(typeof window.addEventListener ! ='undefined') {window.addEventListener('message', onmessage);
}else if(typeof window.attachEvent ! ='undefined') {window.attachEvent('onmessage', onmessage);
}
Copy the code

AJAX requests cross-domain from different sources

Cross domains via JSONP

Rationale: Web pages by adding a

function todo(data){
  console.log('The author is: '+ data.name);
}

var script = document.createElement('script');
script.src = 'http://www.jianshu.com/author?callback=todo';

// Send a request to the server www.jianshu.com. Note that the query string for this request has a callback parameter that specifies the name of the callback function.

document.body.appendChild(script);

// When the server receives the request, it returns the data as an argument to the callback function.

todo({"name": "fewjq"});

// Because the 
Copy the code

Advantages: Compatible with old browsers, background changes small

Disadvantages: Only GET requests are supported

Cross domains via WebSocket

WebSocket is a communication protocol that uses WS :// (non-encrypted) and WSS :// (encrypted) as protocol prefixes. This protocol does not implement the same origin policy, as long as the server support, it can be used for cross-domain communication.

WebSocket request header has a field Origin, indicating the request source (Origin), that is, from the domain name.

It is because of the Origin field that WebSocket does not implement the same Origin policy. Because the server can determine whether to permit this communication based on this field. If the domain name is in the whitelist.

Cross domains through CORS

CORS stands for Cross-Origin Resource Sharing. It is a W3C standard and is a fundamental solution for cross-source AJAX requests. Whereas JSONP can only make GET requests, CORS allows any type of request.

Two kinds of requests

Requests are divided into simple requests and non-simple requests

(1) The request method is one of the following three methods:

  • HEAD
  • GET
  • POST

(2) HTTP 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

A simple request satisfies both of the above conditions

A simple request

If the browser finds that the cross-domain Ajax request is a simple request, it will automatically add the Origin field in the request header with the content of protocol + domain + port

The browser checks to see if the value of the access-control-allow-Origin field in the response is the same as the value of the Origin field, or if it is *. If so, cross-domains are allowed

Non-simple request

For example, content-type is application/json.

Before sending the actual request, the browser sends an OPTION request (precheck request), also checking the access-control-allow-Origin field. After passing, the request is sent normally.