JS front-end to solve the problem of cross-domain 8 kinds of solutions (the latest most complete) _javascript skills

Source: Internet
Author: User
Tags http request script tag

1. The homologous strategy is as follows:

URL Description whether to allow communication
http://www.a.com/A.js
http://www.a.com/B.js
Under the same domain name Allow
http://www.a.com/Lab/a.js
http://www.a.com/Script/b.js
Different folders under the same domain name Allow
Http://www.a.com:8000/a.js
Http://www.a.com/b.js
Same domain, different port Not allowed
Http://www.a.com/a.js
Https://www.a.com/b.js
Same domain, different protocol Not allowed
Http://www.a.com/a.js
Http://70.32.92.74/b.js
Domain name and domain name corresponding IP Not allowed
Http://www.a.com/a.js
Http://script.a.com/b.js
Primary domain is the same, subdomain is different Not allowed
Http://www.a.com/a.js
Http://a.com/b.js
Same domain name, different level two domain name (IBID.) Not allowed (cookies do not allow access in this case)
Http://www.cnblogs.com/a.js
Http://www.a.com/b.js
Different domain names Not allowed

Special attention to two points:

First, if the cross domain problem caused by the protocol and the port is "front desk" is powerless,

Second: On cross-domain issues, domains are identified only by the "header of the URL" and do not try to determine whether the same IP address corresponds to two domains or two domains on the same IP.

"Header of a URL" refers to Window.location.protocol +window.location.host, which can also be understood as "Domains, protocols and Ports match".

2. Front-End resolution of Cross-domain problems

1> Document.domain + iframe (this method is only available when the primary domain is the same)

1) in the 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;
  Operate doc here, that is, b.html
  ifr.onload = null;

2) in the www.script.a.com/b.html:

Document.domain = ' a.com ';

2> Dynamic Script Creation

There's nothing to talk about, because the script label is not limited by the homology policy.

function Loadscript (URL, func) {
 var head = Document.head | | document.getelementbytagname (' head ') [0];
 var script = document.createelement (' script ');
 script.src = URL;

 Script.onload = Script.onreadystatechange = function () {
  if (!this.readystate | | | this.readystate== ' loaded ' | | this.readystate== ' complete ') {
   func ();
   Script.onload = Script.onreadystatechange = null;
  }
 };

 Head.insertbefore (script, 0);
}
Window.baidu = {
 sug:function (data) {
  console.log (data);
 }
}
Loadscript (' Http://suggestion.baidu.com/su?wd=w ', function () {console.log (' Loaded ')});
Where is the content we requested?
//We can see what script introduces in the source of the Chorme debug panel

3> Location.hash + iframe

The principle is to use Location.hash to carry out the value.

Suppose that the file under the domain name a.com cs1.html to communicate with the cs2.html under the cnblogs.com domain name.

1) cs1.html first create an automatic create a hidden iframe,iframe src point to the cs2.html page under the cnblogs.com domain name

2) cs2.html response request will be modified by modifying the cs1.html hash value to pass the data

3 at the same time, add a timer on the cs1.html, at intervals to determine whether the value of Location.hash has changed, once there is a change to get the hash value

Note: Since two pages are not in the same domain IE, chrome is not allowed to modify the value of Parent.location.hash, so to use the A.com domain name under a proxy iframe

The code is as follows:

First the file cs1.html file under a.com:

function Startrequest () {var IFR = document.createelement (' iframe ');
  Ifr.style.display = ' None ';
  IFR.SRC = ' Http://www.cnblogs.com/lab/cscript/cs2.html#paramdo ';
Document.body.appendChild (IFR);
    function Checkhash () {try {var data = Location.hash? location.hash.substring (1): ';
    if (console.log) {console.log (' Now ' the data is ' +data);
The catch (e) {};
} setinterval (Checkhash, 2000);
    cnblogs.com domain name under the cs2.html://Simulate a simple parameter processing operation switch (location.hash) {case ' #paramdo ': CallBack ();
  Break
Case ' #paramset '://do something ... break;
  function CallBack () {try {parent.location.hash = ' somedata '; catch (E) {//IE, Chrome's security mechanism cannot modify parent.location.hash,//So take advantage of an intermediate cnblogs domain under the proxy iframe var ifrproxy = Docume
    Nt.createelement (' iframe ');
    Ifrproxy.style.display = ' None ';  IFRPROXY.SRC = ' Http://a.com/test/cscript/cs3.html#somedata ';
  Note that the file is Document.body.appendChild (ifrproxy) under the "A.com" field;
 }
}

A.com under the domain cs3.html

Because Parent.parent and itself belong to the same domain, you can change the value of its location.hash
Parent.parent.location.hash = self.location.hash.substring (1);

4> Window.name + iframe

The beauty of Window.name: Name values still exist after different pages (or even different domain names) are loaded, and can support very long name values (2MB).

1) Create a.com/cs1.html

2 Create a.com/proxy.html and add the following code

 
 

3 included in the b.com/cs1.html:

<script>
  window.name = ' content to be transmitted ';
</script>

5> PostMessage (API in XMLHttpRequest Level 2 in HTML5)

1) code in a.com/index.html:

<iframe id= "IFR" src= "b.com/index.html" ></iframe>
<script type= "Text/javascript" >
Window.onload = function () {
  var IFR = document.getElementById (' IFR ');
  var targetorigin = ' http://b.com '; If written ' http://b.com/c/proxy.html ' effect
                    is the
  same as//if written ' http://c.com ' will not execute PostMessage Ifr.contentWindow.postMessage (' I was there! ', targetorigin);
</script>

2) code in b.com/index.html:

<script type= "Text/javascript" >
  window.addeventlistener (' message ', function (event) {
    / The Origin property is used to determine the message source address
    if (event.origin = = ' http://a.com ') {
      alert (event.data);  Pop "I was there!"
      alert (Event.source); References to a.com, index.html window objects
                 //But because of the homology policy, the Window object
    }
  , False is not accessible here Event.source;
</script>

6> CORS
The idea behind Cors is to use a custom HTTP header to communicate with the server to determine whether the request or response should be successful or fail.

The implementation of cors in IE is XDR

var xdr = new Xdomainrequest ();
Xdr.onload = function () {
  console.log (xdr.responsetext);
}
Xdr.open (' Get ', ' http://www.baidu.com ');
......
Xdr.send (NULL);

Implementations in other browsers are in XHR

var xhr = new XMLHttpRequest ();
Xhr.onreadystatechange = function () {
  if (xhr.readystate = 4) {
    if (xhr.status >= && xhr.status ; 304 | | Xhr.status = = 304) {
      console.log (xhr.responsetext)
    ;
}}} Xhr.open (' Get ', ' http://www.baidu.com ');
......
Xhr.send (NULL);

Implement Cors across browsers

function createcors (method, url) {
  var xhr = new XMLHttpRequest ();
  if (' Withcredentials ' in xhr) {
    Xhr.open (method, URL, True);
  } else if (typeof xdomainrequest!= ' undefined ') {
    var xhr = new Xdomainrequest ();
    Xhr.open (method, url);
  else{
    xhr = null;
  }
  return xhr;
}
var request = createcors (' Get ', ' http://www.baidu.com ');
if (request) {
  request.onload = function () {
    ...
  };
  Request.send ();
}

7> JSONP

JSONP contains two parts: callback functions and data.

A callback function is a function to be placed on the current page when the response arrives.

The data is the JSON data in the incoming callback function, which is the parameter of the callback function.

function Handleresponse (response) {
  Console.log (' The responsed data is: ' +response.data);
}
var script = document.createelement (' script ');
SCRIPT.SRC = ' http://www.baidu.com/json/?callback=handleResponse ';
Document.body.insertBefore (script, document.body.firstChild);
/*handleresonse ({"Data": "Zhe"})//
principle as follows:
///When we request through the script tag
//Background according to the corresponding parameters (Json,handleresponse)
//To generate the corresponding JSON data (Handleresponse ({"Data": "Zhe"}))
//Finally this returned JSON data (code) will be placed in the current JS file is executed
//So cross-domain communication complete

Jsonp, although simple, has the following drawbacks:

1 security issues (possible security risks in the request code)

2 It is not easy to determine whether the JSONP request fails

8> Web sockets

Web sockets is a browser API that aims to provide full-duplex, two-way communication on a single, persistent connection. (The same origin policy does not apply to Web sockets)

Web Sockets principle: After JS creates a Web socket, an HTTP request is sent to the browser to initiate the connection. When a server response is obtained, the established connection is exchanged with HTTP upgrades from the HTTP protocol to the Web Sockt protocol.

Only work on servers that support the Web socket protocol.

var socket = new Websockt (' ws://www.baidu.com ');//http->ws; Https->wss
socket.send (' Hello Websockt ');
Socket.onmessage = function (event) {
  var data = Event.data;
}

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.