Understanding and realization of cross-domain

Source: Internet
Author: User
Tags http authentication domain server

What is a cross-domain

Domain is a standalone unit in a Windows network, and mutual access between domains requires establishing a trust relationship (that is, trusting Relation). Trust relationships are bridges that connect between domains and domains. When a domain establishes a trust relationship with other domains, the 2 domains can not only manage each other as needed, but also distribute device resources such as files and printers across the network, so that network resources can be shared and managed between different domains. There is a concise explanation for wide-area cross-domain: cross-domain access, which simply means that a site's JavaScript code attempts to access the B site, including submission and access to content. For security reasons, cross-domain access is forbidden by the large browsers.

In a WAN environment, the cross-domain access of a network connection is not allowed due to browser security restrictions, and XMLHttpRequest is no exception. However, sometimes cross-domain access to resources is required.

The same-origin policy prevents scripts loaded from one domain from getting or manipulating document properties on another domain. That is, the domain of the requested URL must be the same as the domain of the current Web page. This means that the browser isolates content from different sources to prevent operations between them. The same-origin policy does not prevent the insertion of dynamic script elements into a document.

Reference theory One: there is no direct cross-domain access in the browser, and there are no cross-domain security restrictions on the server side.

In this case, cross-domain access can be done on the server side, and the results can be achieved on the client.

Reference theory two: the same-origin policy does not prevent dynamic script element insertions, and script access can cross domains.

To resolve cross-domain issues, we can use the following methods:

1 , through Jsonp cross-Domain

The most basic principle of JSONP is: adding a <script> tag dynamically, and the SRC attribute of the script tag is not a cross-domain limitation. In this way, this cross-domain approach is actually unrelated to the Ajax XMLHttpRequest protocol.

In fact, "jquery Ajax cross-domain problem" has become a pseudo-proposition, jquery $.ajax method name is misleading.

If set to datatype: ' Jsonp ', this $.ajax method has nothing to do with Ajax XMLHttpRequest, instead it is the JSONP protocol. JSONP is an unofficial protocol that allows the server-side integration of script tags back to the client to achieve cross-domain access through JavaScript callback.

JSONP is the JSON with Padding. Due to the limitations of the same-origin policy, XMLHttpRequest only allows resources to be requested for the current source (domain name, protocol, port). If cross-domain requests are made, we can make cross-domain requests by using the HTML script tag and return the script code to execute in the response, where the JavaScript object can be passed directly using JSON. This cross-domain communication method is called JSONP.

Jsoncallback function jsonp1236827957501 (...) : A callback function that is registered by the browser client and gets the JSON data on the cross-domain server

The JSONP is executed as follows:

First register a callback (for example: ' Jsoncallback ') on the client, and then pass callback's name (for example: jsonp1236827957501) to the server. Note: After the server gets the value of callback, use jsonp1236827957501 (...). Include the JSON content that will be output, at which point the server generates JSON data to be properly received by the client.

Then, in JavaScript syntax, a function is generated, and the function name is the value jsonp1236827957501 of the parameter ' Jsoncallback ' passed up.

Finally, the JSON data is placed directly into the function in the form of a parameter, so that a document of JS syntax is generated and returned to the client.

The client browser parses the script tag and executes the returned JavaScript document, at which time the JavaScript document data, as parameters, is passed to the client's pre-defined callback function (as in the previous example, jquery $.ajax () Success:function (JSON) in the method encapsulation.

Can say Jsonp way principle and <script src= "//cross-domain/...xx.js" ></script> is consistent (QQ space is a large number of this way to achieve cross-domain data exchange). JSONP is a script injection (scripts injection) behavior, so there is a certain security implications.

So the principle of jsonp is very clear, through the script tag to introduce a JS file, this JS file loading success will execute our function specified in the URL parameters, and we will need to pass the JSON data as parameters. So JSONP is the server side of the page to do the corresponding match.

The advantage of JSONP is that it is not subject to the same-origin policy as Ajax requests implemented by XMLHttpRequest objects, that it is better compatible, that it works in older browsers, and that it does not require XMLHttpRequest or ActiveX support , and after the request is complete, the result can be returned by calling callback.

The disadvantage of JSONP is that it only supports get requests and does not support other types of HTTP requests such as Post, which only supports cross-domain HTTP requests, and does not solve the problem of how to make JavaScript calls between two pages in different domains.

2 , by modifying Document.domain to cross subdomains

Browsers have a single origin policy, one of the limitations of which is that the first method we say cannot be used in Ajax to request documents from different sources. The second limitation is that there is no interaction between the frames of different domains in the browser. It is important to note that different frameworks (parent-child or peer) are able to get to each other's window objects, but the pain is that you can't use the properties and methods of the retrieved window object (the PostMessage method in HTML5 is an exception, Some browsers, such as IE6, can also use a few properties such as top, parent, etc., in short, you can only get to a Window object that is almost useless. For example, there is a page, its address is http://www.example.com/a.html, in this page there is an IFRAME, its src is http://example.com/b.html, it is clear that This page is different from the IFRAME frame inside it, so we can't get the contents of the IFRAME by writing the JS code in the page:

This time, document.domain can come in handy, we just put http://www.example.com/a.html and http://example.com/ B.html the two pages of the document.domain are set to the same domain name can be. Note, however, that the document.domain setting is limited, and we can only set Document.domain to the parent domain of itself or higher, and the primary domain must be the same. For example: The document.domain of a document in a.b.example.com can be set to either a.b.example.com, b.example.com, or example.com, but cannot be set to C.a.b.example.com, because this is a subdomain of the current domain and cannot be set to baidu.com because the primary domain is already different.

Set document.domain in page http://www.example.com/a.html:

In the page http://example.com/b.html also set Document.domain, and this is also necessary, although this document's domain is example.com, However, you must also display the value of the setting Document.domain:

This allows us to access various properties and objects in the IFRAME via JS.

However, if you want to request the http://example.com/b.html page directly via Ajax in the Http://www.example.com/a.html page, Even if you set the same document.domain is still not working, so the method of modifying Document.domain only applies to the interaction between the frameworks of different subdomains. If you want to use AJAX methods to interact with different subdomains of the page, in addition to using the Jsonp method, you can also use a hidden iframe to do a proxy. The idea is to have this iframe load a page in the same domain as the target page you want to get data from Ajax, so the page in this IFRAME can use Ajax to get the data you want, Then it is through the method we have just said to modify document.domain, so that we can fully control the IFRAME through JS, so that we can let the IFRAME to send AJAX requests, and then receive the data we can get.

3 , using Window.name to perform cross-domain

The Window object has a Name property that has a feature: that is, within the lifetime of a window, All the pages loaded in the window are shared by a window.name, each page has read and write permissions to Window.name, Window.name is persisted on all pages loaded by a window and will not be reset due to the loading of the new page.

For example: There is a page a.html, it has such code:

Then look at the code for the b.html page:

A.shtml page loading 3 seconds, jump to the b.html page, the result is:

We see that on the b.html page, we successfully obtained the value of the previous page a.html to Window.name set. If the window.name is not modified by all the loaded pages after that, then all of the window.name values obtained by these pages are the values a.html the page settings. Of course, if necessary, any one of these pages can modify the value of Window.name. Note that the value of the window.name can only be in the form of a string, the maximum size of the string can allow 2M or even a larger capacity, depending on the browser, but generally enough.

In the above example, the pages a.html and b.html are in the same domain, but even if a.html and b.html are in different domains, the same conclusion applies, and this is the principle of cross-domain using Window.name.

Here's a look at how to get data across domains through Window.name. or an example.

For example, there is a www.example.com/a.html page, you need to a.html the page JS to get another page located in different fields www.cnblogs.com/data.html data. The code in the Data.html page is very simple, which is to set the current window.name to the data value that the A.html page wants to get. The code in data.html:

So in the A.html page, how do we load the data.html page into it? Obviously we can't load the data.html page directly on the a.html page by changing the window.location, because we want to get the data in data.html even if the a.html page doesn't jump. The answer is to use a hidden iframe in the a.html page to act as a man-in-the-middle character, to get data.html data from the IFRAME, and then a.html to get the data that the IFRAME gets.

An IFRAME that acts as a middleman wants to get to Data.html's data through Window.name, just set the SRC to www.cnblogs.com/data.html. Then a.html want to get the data obtained by the IFRAME, that is, want to get the window.name of the IFRAME value, you must also set the IFRAME src to the same domain as the a.html page, otherwise, according to the same homologous strategy, a.html is not accessible to the IFRAME of the Window.name property. This is the entire cross-domain process.

Look at the code for the a.html page:

4 , using HTML5 The introduction of the new Window.postmessage method to transfer data across domains

The Window.postmessage (Message,targetorigin) method is a newly introduced feature of HTML5 that can be used to send messages to other window objects, regardless of whether the window object belongs to the same origin or different source, currently ie8+, Browsers such as FireFox, Chrome, and opera already support the Window.postmessage method.

The Window object that invokes the PostMessage method refers to the window object that receives the message, the first parameter of the method is the message to be sent, and the type can only be a string The second parameter, Targetorigin, is used to qualify the domain of the Window object that receives the message, and if you do not want to qualify the domain, you can use the wildcard character *.

The window object that needs to receive the message, but receives the message by listening to its own message event, which is stored in the event object's Data property.

As mentioned above, sending a message to another window object is actually a case where a page has several frames, because each frame has a window object. In discussing the second approach, we have said that the frames of different domains can be obtained from each other's window object, and you can also use the Window.postmessage method.

Sencha Touch How to handle cross-domain

A new feature under modern browsers is the Cors (cross-origin Resource sharing) cross-domain request. This feature allows you to send requests to other domain domains and is not subject to browser security restrictions. Sencha TOUCH2 has supported this approach, but you also need to do some Web server-side setup to start Cors.

Ext.Ajax.request ({
URL: ' http://www.somedomain.com/some/awesome/url.php ',
Withcredentials:true,
Usedefaultxhrheader:false
});

The Withcredentials property is what we have to configure, the default is false, and it must be set to True if a cors request is required; By default, cross-domain requests do not provide credentials (cookies, HTTP authentication, and client SSL certificates, etc.). By setting the Withcredentials property to True, you can specify that a request should send credentials. If the server receives a request with credentials, it responds with the HTTP header below. The Usedefaultxhrheader property is set to False. Make each request not send a default XHR header (X-requested-with).

Understanding and realization of cross-domain

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.