Cross-domain solution introduction 2, transferred from github.

Cross-domain solution introduction 2, transferred from github.

Cross-domain issues

The cornerstone of browser security is the "same-origin policy." The so-called homologous refers to the same protocol, the same domain name, and the same port. As long as one of them is different, it is called a different source. Websites from different sources cannot request data from each other to ensure the security of user data. But sometimes, a website has to request data from other domains. This process is called cross-domain.

There are several ways to implement cross-domain:


The principle of JSONP (JSON with padding) is that the script tag is not restricted by the same-origin security policy, and it can send get requests to other domains.

function handleResponse(data) {
	console.log('The response data is:' + data);
//Add script tags dynamically
var script = document.createElement('script');
script.src ='';

After receiving the get request in the background, it generates the corresponding JSONP data handleResponse({'data': serverdata}) according to the callback parameters  . This piece of data is returned to the front end and executed as js code, triggering the callback function.

jQuery and JSONP

		async: false,
		//Query the information of CA1998 flight
		//Passed to the request handler or page to obtain the parameter name of the jsonp callback function name (generally default: callback)
		//Customized jsonp callback function name, the default is the random function name automatically generated by jQuery, you can also write "?", jQuery will automatically process the data for you
		success: (json) => {
			alrt('The flight information you found: fare: '+ json.price +' yuan, remaining tickets: '+ +' tickets.');
		error: () => {

(2) CORS

CORS is a W3C standard, the full name is cross-origin resource sharing, which allows browsers to send XMLHttpRequest requests to cross-origin servers, thus overcoming the restriction that AJAX can only be used from the same source.

The entire CORS communication process is automatically completed by the browser, and the user does not need to participate. For front-end developers, the codes of the same source Ajax and CORS are exactly the same. Therefore, the key to implementing CORS is whether the server provides a CORS interface.

Simple request example:

GET/cors HTTP/1.1
Accept-Language: en-US
Connection: keep-alive
User-Agent: Mozilla/5.0...

If the server allows cross-domain requests from, it will respond as follows:

Access-Control-Allow-Credentials: true//whether to allow cookies to be sent
Access-Control-Expose-Headers: FooBar//additional header field
Content-Type: text/html; charset=utf-8

If it is not allowed, the Access-Control-Allow-Origin field will not be set. If the server sets this field to *, it means that the server accepts cross-domain requests from all domains.

Access-Control-Allow-Credentials: true means that the server accepts cookies, and the developer should open the withCredentials property in AJAX to allow the browser to send cookies:

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

Cross-domain resource sharing CORS detailed explanation

(3) iframe + HTML5 postMessage

That is to say , cross-domain communication is carried out between different windows through the HTML5 API  postMessage , and the format is:

otherWindow.postMessage(data, targetOrigin);
//otherWindow refers to the window to receive the message, targetOrigin limits the domain of the receiving window, if you don’t want to limit it, just set it as *


<iframe id="ifr" src=""></iframe>
<script type="text/javascript">
window.onload = function() {
    var ifr = document.getElementById('ifr');
    var targetOrigin ='';//The effect is the same if written as''
                                       //If it is written as'', postMessage will not be executed
    ifr.contentWindow.postMessage('Message from!', targetOrigin);
<script type="text/javascript">
    window.addEventListener('message', function(event){
       //Determine the source address of the message by the origin attribute
        if (event.origin =='') {
            alrt(;//"Message from!" pops up
            alrt(event.source);//Reference to the window object in and index.html
                                 //But due to the same-origin policy, event.source cannot access the window object here
    }, false);

(4) iframe +

Principle: The value of still exists after different pages (even different domain names) are loaded, and can support very long name values ​​(2MB)

<script type="text/javascript">
function getData() {
	var ifr = document.getElementById('proxy');
	ifr.src ='';//Jump to the same-source website
	ifr.onLoad = function() {
		var data =;
<iframe src='http://other-origin/data.html' style='display:none' onLoad='getData()'></iframe>


var data = {
	age: 12
}; = JSON.stringify(data);


WebSocket is a communication protocol that uses ws://(non-encrypted) and wss://(encrypted) as the protocol prefix. This protocol does not implement the same-origin policy, as long as the server supports it, cross-origin communication can be carried out through it.

Request header information: (more origin)
GET/chat HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13

Response header: (if origin is in the whitelist)
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=
Sec-WebSocket-Protocol: chat
Reference: Cross-domain solution introduction 2, transferred from github.-Cloud + Community-Tencent Cloud