JS cross-domain

Source: Internet
Author: User
Tags subdomain

Transfer from https://www.cnblogs.com/yongshaoye/p/7423881.html

First, understand the cross-domain?

1 concept: As long as the protocol, domain names, ports are any different, are considered to be different domains.

Definition: cross-domain refers to a resource that requests another domain name from a Web page of a domain name. For example, from the Www.baidu.com page to request www.google.com resources. However, in general, it is not possible to do so, it is caused by the browser's homologous policy, is the browser security restrictions imposed on JavaScript.

The so-called homologous refers to the domain name, protocol, ports are the same. The JS cross-domain refers to the data transfer or communication between different domains via JS, such as using AJAX to request data from a different domain, or by JS to get the frames (IFRAME) of the different domains in the page.

Note: Both localhost and 127.0.0.1 are pointing to native, but also cross-domain.

When the browser executes a JavaScript script, it checks which page the script belongs to and is not executed if it is not a homologous page.

The differences between ports and protocols can only be resolved through the background.

2 cases:

Http://www.123.com/index.html Call Http://www.123.com/server.PHP (non-cross-domain)

Http://www.123.com/index.html call http://www.456.com/server.php (primary domain different: 123/456, cross-domain)

Http://abc.123.com/index.html Call http://def.123.com/server.php (different sub-domains: abc/def, cross-domain)

Http://www.123.com:8080/index.html Call http://www.123.com:8081/server.php (Port different: 8080/8081, cross-domain)

Http://www.123.com/index.html Call https://www.123.com/server.php (protocol differs: Http/https, cross-domain)

Second, why do browsers restrict cross-domain access?

The reason for this is security: if a webpage can freely access the resources of another site, then it is possible to have a security problem without the customer knowing it completely. For example, the following operations have security issues:

    1. The user accesses the www.mybank.com, logs in and carries on the net silver operation, at this time the cookie all generates and stores in the browser
    2. The user suddenly remembered something, and stumbled over an evil site to visit www.xiee.com
    3. At this point, the site can be on its page, to get the bank's cookie, such as user name, login token, etc., and then initiate the operation of the www.mybank.com.
    4. If the browser is not limited at this point, and the bank does not respond to the security processing, then the user's information may be so leaked.
Third, why cross-domain?

Now that there is a security problem, why cross-domain again? Sometimes the company has a number of different sub-domains, such as a location.company.com, and the application is placed in app.company.com, then want to access from app.company.com location.company.com Resources belong to a cross-domain.

(1) Cross-domain resource sharing (CORS)

Only need to add a response header in the background to allow the domain request! Cross-domain access is possible by adding the following settings to the requested response header!

Specify allow other domain names to access ' access-control-allow-origin:* '//or specify domain//response type ' access-control-allow-methods:get,post '//Response header Settings ' Access-control-allow-headers:x-requested-with,content-type '
(2) Cross-domain via JSONP (only get requests are supported, other request methods are not supported)

Jsonp principle : Through the script tag to introduce a JS file, this JS file loaded successfully will execute the function we 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. (i.e. dynamically loading a script file with JavaScript and defining a callback function for script execution.) )

In JS, it XMLHttpRequest is not possible for us to request data directly from different domains. However, it is possible to introduce JS script files on different domains on the page, and JSONP is using this feature to achieve this. For example:

JS Code

<Scripttype= "Text/javascript">    functiondosomething (jsondata) {//processing the obtained JSON data    }</Script><Scriptsrc= "Http://example.com/data.php?callback=dosomething"></Script>

PHP code

<? php$callback = $_get[' callback '];//gets the callback function name $data = Array (' A ', ' B ', ' C '),//The data to be returned echo $callback. ' ('. Json_encode ($data). ') '; /output ?>

If you use jquery, the $.getJSON method will automatically determine if it is cross-domain, not cross-domain, call ajax the normal method, cross-domain, it will be the form of asynchronous loading JS file to invoke jsonp the callback function. Such as:

<type= "Text/javascript">    $.getjson ('  Http://example.com/data.php?callback=?,function (jsondata)') {        //  Processing of the obtained JSON data     }); </ Script >
(3) Cross-subdomain by modifying Document.domain

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.
A Window object can be obtained between different frames, but the corresponding properties and methods cannot be obtained. For example, there is a page, its address is http://www.example.com/a.html , in this page there is a iframe , its src is http://example.com/b.html , it is clear that this page and its iframe framework is different domain, so we are not able to write in the page JS code to get iframe things in:

<script type= "Text/javascript" >    function Test () {        var iframe = document.getElementById ('? Ifame ');        var win = document.contentwindow;//can get to the Window object in the IFRAME, but the properties and methods of the Window object are almost unusable        var doc = win.document;// The Document object in the IFRAME is not available here        var name = win.name;//Here also gets the Name property of the Window object    }</script><iframe id = " iframe "src=" http://example.com/b.html "onload =" test () "></iframe>

This time, document.domain It can come in handy, we just have to http://www.example.com/a.html the http://example.com/b.html 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.

1. On the page, http://www.example.com/a.html set document.domain :

<iframe id = "iframe" src= "http://example.com/b.html" onload = "test ()" ></iframe><script type= "text/ JavaScript ">    document.domain = ' example.com ';//Set as Primary domain    function test () {        alert ( document.getElementById ('? iframe '). Contentwindow);//contentwindow can get the window object of the Subwindow    }</script>

2. http://example.com/b.html also set in the page document.domain :

<script type= "Text/javascript" >    document.domain = ' example.com ';// In the iframe loading this page also set Document.domain to make it the same as the document.domain on the main page </script>

document.domainthe modified method only applies to the interaction between frames of different subdomains .

(4) using Window.name for 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. Such as:

On the b.html page, you successfully obtained the value that was set on the previous page a.html to Window.name. 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.

The pages we use a.html and b.html are in the same domain, but even if a.html and b.html are in different domains, the same is true of the above conclusions, which is the principle of cross-domain using Window.name.

JS 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.