Javascript cross-origin solution (1)

Source: Internet
Author: User

 

1. Shenma is a Cross-Domain)

The white point is that the post and get URLs are not your current website, and the domain names are different. For example, in aaa.com/a.html, the table Ticket delivery action is bbb.com/ B .html.

In addition, www.aaa.com and aaa.com are also cross-domain because www.aaa.com is a second-level domain name and aaa.com is a root domain name.

For security reasons, JavaScript does not allow cross-Origin calls to objects on other pages (Same-Origin Policy ).

For a detailed description of whether JavaScript can communicate across regions, see the following table:

Http://www.a.com/a.jsAccess the following URL results

URL Description Allow communication?
Http://www.a.com/ B .js Under the same domain name Allow
Http://www.a.com/script/ B .js Different folders under the same domain name Allow
Http://www.a.com: 8000/B. js Different ports for the same domain name Not Allowed
Https://www.a.com/ B .js Different protocols for the same domain name Not Allowed
Http: // 70.32.92.74/B. js Corresponding ip addresses of domain names and domain names Not Allowed
Http://script.a.com/ B .js The primary domain is the same and the subdomain is different. Not Allowed
Http://a.com/ B .js Same domain name, different second-level domain names (same as above) Not Allowed
Http://www. B .com/ B .js Different domain names Not Allowed

 

2. Why cross-origin?

Cross-origin is actually very common. For example, we can place some scripts, images, or other resources of a website on another site. For example, we can use jQuery provided by Google, which reduces loading time and server traffic, as shown below:

<Script type = "text/java script" src = "https: // aja x.googleapis.com/aj ax/libs/jquery/1.4.2/jquery. min. js"> </script>

Sometimes we want to call some data (sometimes we have to do this) from other sites, not just resources such as scripts and images ), for example, if I want to get some blog RSS to generate some content, or if I develop an application on the "Everyone open platform", I need to call everyone's data.

However, unfortunately, using XMLHttpRequest for Get or Post won't work. For example, I use jQuery's $. get to access the main domain name of this blog:

$. Get ("http://flycoder.org /",

{}, Function (data ){

Alert ('cross-origin is not jailbroken: '+ data)

}, "Html ");

The result is as follows ~ FF does not report an error, but wood has returned data ):

 

What should I do? (Weakly speaking, during the test, I found that Internet Explorer can access local files across domains, but this is useless ~ Token ~)

3. Swollen cross-Origin

For better explanation and test, we can modify the hosts file to simulate the cross-origin effect. The hosts file is in the C: \ Windows \ System32 \ drivers \ etc folder. Add three lines below:

127.0.0.1 www.a.com

127.0.0.1 a.com

127.0.0.1 www. B .com

3.1 cross-origin proxy

A simple method is to hand over Cross-origin work to the server, obtain data from other sites in the background, and then return the data to the front-end, that is, Cross-Domain Proxy ).

This method seems quite simple, and the changes are not great. However, the http request is a little longer, the response is slower, and the server load is heavier ~

 

3.2. document. domain + iframe

 

 

For examples with the same primary domain and different subdomains, you can set document. domain.

For example, a primary domain name can only be used as the primary domain name. The two pages can access each other. The Code is as follows:

Script in www.a.com/a.html

Document. domain = 'a. com ';

Var ifr = document. createElement ('iframe ');

Ifr. src = 'HTTP: // a.com/ B .html ';

Ifr. style. display = 'none ';

Document. body. appendChild (ifr );

Ifr. onload = function (){

// Obtain the document Object of iframe

// The W3C standard method is iframe. contentDocument,

// Ie63167you can use document.frames?id=.doc ument

// For better compatibility, You can first obtain the iframe window object iframe. contentWindow

Var doc = ifr. contentDocument | ifr.content##doc ument;

// Operate B .html here

Alert (doc. getElementById ("test"). innerHTML );

};

 

A.com/ B .html

<! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN">

<Html>

<Head>

<Title> </title>

<Script type = "text/javascript">

Document. domain = 'a. com ';

</Script>

</Head>

<Body>

<H1 id = "test"> Hello World

</Body>

</Html>

If B .html wants to parse a.html, you can use window in the subwindow (iframe. parent to access the window object of the parent window, and then you can do whatever you want (the window object has something else, and nothing else). Similarly, the Child window can communicate with the child window.

Therefore, we can pass B .html's xmlhttprequestto obtain data and then send it to a.html to solve the problem of cross-subdomain data acquisition.

However, this method only supports pages under the same root domain name. If different root domain names (such as baidu.com want to access google.com), there is no way to do it.

 

3.3 Dynamic script Tag (Dynamic Script Tag)

This method is also called "dynamic Script Injection ". Details

This technology overcomes the maximum limit of XMLHttpRequest, that is, cross-origin request data. Directly create a new script tag using JavaScript, and set its src attribute to the URL of different domains.

Script in www.a.com/a.html

Var dynScript = document. createElement ('script ');

DynScript. src = 'HTTP: // www. B .com/ B .js ';

DynScript. setAttribute ("type", "text/javascript ");

Document. getElementsByTagName ('head') [0]

. AppendChild (dynScript );

Dynamic tag injection must be executable JavaScript code. Therefore, whatever your data format (such as xml and json), it must be encapsulated in a callback function. A callback function is as follows:

Script in www.a.com/a.html

Function dynCallback (data ){

// Process data.

Alert (data. content );

}

In this example, www. B .com/ B .js blocks the data in the dyncallback, as shown below:

1

DynCallback ({content: 'Hello world '})

We have seen a pleasant result, Hello World ~

 

 

 

However, there are still many problems with dynamic Script Injection. let's compare it with XMLHttpRequest:

  XmlHttpRequest Dynamic Script Tag
Cross-browser compatibility No Yes
Cross-origin restrictions Yes No
Receive HTTP status Yes No (except 200)
Support for Get and Post Yes No (GETOnly)
Send and receive HTTP headers Yes No
Receive XML Yes Yes
Receive JSON Yes Yes
Synchronous and asynchronous Yes No (asynchronous only)

 

It can be seen that there are still many restrictions on dynamic Script Injection. Only Get can be used, and Http status cannot be determined like XHR.

Note the following when using dynamic Script Injection:Security Questions. Because JavaScript does not have any permissions and access control concepts, the code injected by dynamic scripts can completely control the entire page. Therefore, you must be careful when introducing code from external sources.

 

 

Author: jiangzhenghua

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.