Cross-domain Method collation

Source: Internet
Author: User

you must understand the same-origin policy before speaking across domains: homologous strategy, which is a well-known security policy proposed by Netscape. This policy is now used by all JavaScript-enabled browsers. The so-called homology refers to the same domain name, protocol, and port. When a browser's two tab pages are opened to Baidu and Google's page when a Baidu browser executes a script will check which page this script belongs to, that is, check whether the same origin, only and Baidu homologous script will be executed. The simple sentence is: " if two pages have the same protocol (protocol), the port (if specified), and the host, then the two pages belong to the same source (origin)." "For whether the same origin:

  

In order to ensure the security of user information, to prevent malicious websites to steal data. Under the same origin policy: cookies, localstorage, and indexdb cannot be read, DOM cannot be obtained, and AJAX requests cannot be sent. (PS: If you want to learn more about the same-origin strategy, you can look at Ruan Feng's blog: http://www.ruanyifeng.com/blog/2016/04/same-origin-policy.html).

In order to resolve communication between different sources, cross-domain is thus born:

    Method One: JSONP

JSONP:JSONP is the short name of JSON with padding, and Jsonp looks like JSON, just JSON data contained in a function.

Callback ({"Name": "Xiaotutu"});

Because the script tag is not affected by the same origin policy, it can introduce a JS file from anywhere. The JSONP principle is that a function is defined on the client and the server, and when the client initiates a request, the server returns a piece of JavaScript code that invokes the function defined on the client and passes the corresponding data as a parameter to the function. In general, in order for this script tag to be dynamically invoked, we can dynamically create the script tag through JavaScript, so that we have the flexibility to invoke the remote service. The code is as follows:

        

function Jsonp_callback (data) {    console.log (data);} function Jsonpajax () {    var'http://a.com/b.php?jsonp_callback=jsonp_callback " ;     var script = document.createelement ('script');     // Send Request    script.src = URL;    Document.head.appendChild (script);} Jsonpajax ()

When the server accepts the callback, it returns the corresponding code.

Jsonp_callback ({   "name": "Chentutu"});

Jsonp is a simple, flexible use of <script> 's unrestricted access to load resources from other domains. Because JavaScript is a valid code, it is executed immediately after the request is completed.

Method Two:

As with script, you can load resources from other domains, using their onload and onerror event handlers to determine whether they are responding. But it can only be used to send a GET request, and cannot get the response text on the server side, so it can only be used to implement some simple, one-way cross-domain communication, such as tracking user clicks. Let's take a look at the following example:

var New  function() {    console.log (' Done ')    null;     NULL  = "Http://xx/xx.gif"

Method Three: CORS

CORS (Cross-origin Resource sharing, cross-origin resource sharing) is a standard developed by the group that allows browsers to implement cross-domain communication. By creating a XMLHttpRequest object, Cors allows the developer to implement cross-origin requests as if it were a homologous request. The goal of CORS (cross-origin resource sharing) is very simple to achieve. Assuming that site B wants to access some of the data in site A, using the same-origin request will not meet this requirement. However, with Cors requests, site A can allow site B access by adding a special response header to some pages.

Note Cors supports only the following browsers:

    • Chrome version 3 and above browser
    • Firefox 3.5 or later browser
    • Safari 4 or above version of browser
    • Internet Explorer version 8 and above browser

Here is a code to create the request object:

 functioncreatecorsrequest (method, url) {varXHR =NewXMLHttpRequest (); if("Withcredentials"inchxhr) {        //checks if the XMLHttpRequest object has a Withcredentials property        //Withcredentials Property belongs to XMLHTTPRequest2 object onlyXhr.open (method, URL,true); }     Else if(typeofXdomainrequest! = "undefined") {        //Otherwise, examine the Xdomainrequest object Otherwise, check if xdomainrequest.        //The Xdomainrequest object exists only in Internet Explorer and is used by IE to create cors requestsXHR =Newxdomainrequest ();    Xhr.open (method, URL); }     Else {        //Otherwise, cors is not supported by the current browserXHR =NULL; }    returnxhr;}varXHR = createcorsrequest (' GET ', URL);if(!xhr) {    Throw NewError (' cors is not supported! ‘);}

By default, standard Cors requests do not send or set any cookies. In order to include cookies in the request, you need to set the Withcredentials property value of the XMLHttpRequest object to True. To achieve this, the server side must set the Access-control-allow-credentials response header to true: the setting of the Withcredentials property value will allow any cookie to be included in the cross-origin request. Developers can also use this property value to set any cookie across the source. Note that these cookies can also use the same-origin security policy, where the contents of cookies set by cross-origin cannot be accessed by the same source JavaScript script code, and can only be accessed by the sources that set these cookies.

An example of a complete code that uses Cors requests is shown below:

//Create a Xhr objectfunctioncreatecorsrequest (method, url) {varXHR =NewXMLHttpRequest (); if("Withcredentials"inchxhr) {        //Chrome/safari/firefox XHR objects in the browserXhr.open (method, URL,true); }     Else if(typeofXdomainrequest! = "undefined") {        //Create a Xdomainrequest object in IE browserXHR =Newxdomainrequest ();    Xhr.open (method, URL); }     Else {        //Cors is not supported.XHR =NULL; }    returnxhr;}//get the title tag from the server-side responsefunctionGetTitle (text) {returnText.match (") [1];}//Create a cors requestfunctionmakecorsrequest () {//bibliographica.org support for cors requests    varurl = ' http://bibliographica.org/'; varXHR = createcorsrequest (' GET ', URL); if(!xhr) {Alert (' Your browser does not support cross-origin requests '); return; }    //Handling server-side responsesXhr.onload =function() {        varText =Xhr.responsetext; vartitle =getTitle (text); Alert (' from ' + URL + ' response: ' +title);    }; Xhr.onerror=function() {alert (' Cross-origin request failed! ‘);    }; Xhr.send ();}

Cors is divided into simple and non-simple modes: For details, please see Ruan Yi-Feng's blog: http://www.ruanyifeng.com/blog/2016/04/cors.html.

method Four: Document.domain

    • Principle: The same primary domain name under different sub-domain pages, you can set them to the document.domain same domain
    • Limitations: The same domain document provides interoperability between pages and needs to be loaded into the IFRAME page

Here is the code that Document.domain actually operates:

var ifr = document.createelement (' iframe '= ' Http://b.a.com/bar 'function() {     var ifrdoc = Ifr.contentdocument | | ifr.contentWindow.document;    Ifrdoc.getelementsbyid ("foo"= ' None ';d ocument.body.appendChild (IFR);

Note: If Document.domain is modified, IE678 on some machines gets location.href with permission exceptions. document.domainIt can only be set from the subdomain to the primary domain, and setting down and toward other domain names is not allowed.

Method Five: Window.postmessage

    • Principle: HTML5 allow messages to be sent between windows
    • Limitations: Browsers need to support HTML5 to get window handles before they can communicate with each other
// Send Side var win = window.open (' Http://b.com/bar '); Win.postmessage (' Hello world! ', ' http://b.com '  // receive end Window.addeventlistener (' message ',function(event) {    console.log (event.data);});

Want to know window.postmessage bo friends can see Zhang Xinxu Teacher's blog: http://www.zhangxinxu.com/wordpress/2012/02/ html5-web-messaging-cross-document-messaging-channel-messaging/.

Method Six: WebSocket

WebSocket is a new protocol for HTML5. It implements full-duplex communication between the browser and the server, while allowing cross-domain communication, which is a great implementation of server push technology. (No HTTP protocol has its own set of protocols).

On the client's instance:

varWS =NewWebSocket (' Ws://127.0.0.1:8080/url ');//Create a new WebSocket object, note that the server-side protocol must be "ws://" or "wss://", where WS begins with a normal websocket connection, and WSS is a secure websocket connection, similar to HTTPS. Ws.onopen =function() {    //called when the connection is opened};ws.onerror=function(e) {//called when an error occurs, such as when the connection is broken};ws.onclose=function() {    //called when the connection is closed};ws.onmessage=function(msg) {//called when a message is sent to the client on the server side    //Msg.data contains the message};//here is how to send some data to the server sideWs.send (' Some data ');//closing the Socket interfaceWs.close ();

For details, let's look at Red Book 591.

Cross-domain Method collation

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.