JS Cross-domain method

Source: Internet
Author: User
Tags subdomain

JavaScript cross-domain Summary and solutions

    • What is a cross-domain
    • 1, the Document.domain+iframe setting
    • 2. Create script dynamically
    • 3. Using IFRAME and Location.hash
    • 4, Window.name realization of cross-domain data transfer
    • 5. Use HTML5 postMessage
    • 6. Using Flash

This article is from the network (http://f2e.me/200904/cross-scripting/, which is inaccessible), only for personal reading notes, and slightly modified and supplemented.

What is a cross-domain

JavaScript is not allowed to invoke objects of other pages across domains for security reasons. But the security restrictions also bring a lot of trouble to inject IFRAME or AJAX applications. Here are some simple things to sort out about cross-domain issues:

First what is cross-domain, simple to understand is because of the JavaScript homologous policy limitations, a.com domain name JS can not operate B.Com or c.a.com under the domain name of the object. A more detailed explanation can be seen in the following table:

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 name, different ports

Not allowed

Http://www.a.com/a.js

Https://www.a.com/b.js

Same domain name, different protocols

Not allowed

Http://www.a.com/a.js

Http://70.32.92.74/b.js

Domain 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 are also not allowed in this case)

Http://www.cnblogs.com/a.js

Http://www.a.com/b.js

Different domain names

Not allowed

Pay special attention to two points:

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

Second: On a cross-domain issue, the domain is only identified by the "header of the URL" and does not attempt to determine whether the same IP address corresponds to two domains or two domains on the same IP.

The "header of the url" refers to Window.location.protocol +window.location.host, which can also be understood as "Domains, protocols and ports must match".

Then briefly summarize in the "front desk" generally handle cross-domain approach, background Proxy This scenario involves the background configuration, here is not elaborated, interested can see Yahoo this article: "Javascript:use a Web Proxy for Cross-domain XMLHttpRequest Calls "

1, the Document.domain+iframe setting

For examples where the primary domain is the same and the subdomain is different, it can be resolved by setting the Document.domain method. Specifically, the http://www.a.com/a.html and http://script.a.com/b.html two files can be added document.domain = ' a.com ' And then create an IFRAME in the a.html file to control the contentdocument of the IFRAME so that the two JS files can "interact" with each other. Of course, this approach can only solve the same primary domain and the two-level domain name is different, if you whimsical script.a.com Domian set to Alibaba.com that obviously will be error! The code is as follows:

The a.html on the www.a.com

Document.domain = ' a.com ';
var IFR = document.createelement (' iframe ');
IFR.SRC = ' http://script.a.com/b.html ';
Ifr.style.display = ' None ';
Document.body.appendChild (IFR);
Ifr.onload = function () {
var doc = Ifr.contentdocument | | Ifr.contentWindow.document;
Manipulating the b.html here.
Alert (Doc.getelementsbytagname ("H1") [0].childnodes[0].nodevalue);
};

The b.html on the script.a.com

Document.domain = ' a.com ';

This approach applies to any page in {www.kuqin.com, kuqin.com, script.kuqin.com,css.kuqin.com} to communicate with each other.

Note: The domain default for a page is equal to Window.location.hostname. The primary domain is a domain name without www, such as a.com, which is usually preceded by a two-level domain name or a multilevel domain name, such as Www.a.com, which is actually a two-level domain name. Domain can only be set as the primary domain name, and domain can not be set to c.a.com in B.a.com.

Problem:

1, security, when one site (b.a.com) is attacked, another site (c.a.com) can cause security vulnerabilities.

2, if a page to introduce multiple IFRAME, to be able to operate all the IFRAME, you must set the same domain.

2. Create script dynamically

Although the browser prohibits cross-domain access by default, it does not prohibit referencing other domain's JS files in the page, and can freely execute the function in the introduced JS file (including manipulating cookies, DOM, etc.). Based on this, it is convenient to create a script node to achieve complete cross-domain communication. The specific practice can refer to Yui's getutility

It's pretty interesting to judge that the script node is loaded: IE can only pass the script's ReadyStateChange property, and the other browser is the Load event for the script. Here are some ways to determine the completion of script loading.

Js.onload =js.onreadystatechange = function () {
if (!this.readystate | | This.readystate = = = ' Loaded ' | | This.readystate = = = ' complete ') {
Callback is executed here
Js.onload = js.onreadystatechange= null;
}
};

3. Using IFRAME and Location.hash

This method is more round, but it can solve the problem of footstep replacement in the case of complete cross-domain. The principle is to use Location.hash to transmit values. In the Url:http://a.com#helloword ' #helloworld ' is location.hash, changing the hash does not cause the page to refresh, so you can use the hash value for data transfer, of course, the data capacity is limited. Assuming that the file under the domain name a.com cs1.html to and cnblogs.com the cs2.html of the domain name, cs1.html first creates a hidden iframe,iframe that automatically creates a cnblogs.com page under the cs2.html domain name The ash value can be used for parameter passing. The cs2.html responds to the request and then passes the data by modifying the hash value of the cs1.html (because two pages are not in the same domain ie, Chrome does not allow you to modify the value of Parent.location.hash, so you can modify it by using an agent Iframe;firefox under the a.com domain name. At the same time, add a timer on the cs1.html, interval time to determine whether the value of Location.hash has changed, a little change gets the hash value. The code is as follows:

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

Functionstartrequest () {
var IFR =document.createelement (' iframe ');
Ifr.style.display = ' None ';
IFR.SRC = ' Http://www.cnblogs.com/lab/cscript/cs2.html#paramdo ';
Document.body.appendChild (IFR);
}

Functioncheckhash () {
try {
var data = Location.hash? location.hash.substring (1): ";
if (Console.log) {
Console.log (' Now the data is ' +data);
}
} catch (e) {};
}
SetInterval (CheckHash, 2000);

Cs2.html under the cnblogs.com domain name:

Simulates a simple parameter handling operation
Switch (Location.hash) {
Case ' #paramdo ':
CallBack ();
Break
Case ' #paramset ':
Do something ...
Break
}

Functioncallback () {
try {
Parent.location.hash = ' Somedata ';
} catch (e) {
IE, chrome security mechanism can not modify the Parent.location.hash,
So we're going to use a proxy iframe in the middle of the cnblogs domain.
var ifrproxy = document.createelement (' iframe ');
Ifrproxy.style.display = ' None ';
IFRPROXY.SRC = ' Http://a.com/test/cscript/cs3.html#somedata '; Note that the file is under the "a.com" field
Document.body.appendChild (Ifrproxy);
}
}

The domain name under a.com cs3.html

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

Of course, there are many shortcomings, such as data directly exposed to the URL, data capacity and type are limited, etc...

4, Window.name realization of cross-domain data transfer

Articles longer listed here are not easy to read, see the window.name implementation of cross-domain data transfer.

5. Use HTML5 postMessage

One of the coolest new features in HTML5 is the cross-document message transfer crossdocument Messaging. Next-generation browsers will support this feature: Chrome 2.0+, Internet Explorer 8.0+, Firefox 3.0+, Opera 9.6+, and Safari 4.0+. Facebook has used this feature to support web-based real-time messaging with PostMessage.

Otherwindow.postmessage (Message,targetorigin);

Otherwindow: A reference to the window that receives the information page. This can be the Contentwindow property of the IFrame in the page, the return value of the window.open, or the value taken from the Window.frames by name or subscript.

Message: The data to be sent, string type.

Targetorigin: Used to limit Otherwindow, "*" means no restrictions

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 it's written as ' http://b.com/c/proxy.html ' effect
If you write ' http://c.com ', you won't execute postmessage.
Ifr.contentWindow.postMessage (' I wasthere! ', targetorigin);
};
</script>

Code in b.com/index.html:

<scripttype= "Text/javascript" >
Window.addeventlistener (' message ', function (event) {
To determine the source address of a message by Origin property
if (Event.origin = = ' http://a.com ') {
alert (event.data); Eject "I was there!"
alert (Event.source); A reference to the Window object in A.com, index.html
However, due to the same Origin policy, Event.source cannot access the window object here
}
}, False);
</script>

Reference article: Master HTML5 Programming Fifth-cross-document messaging mechanism, Https://developer.mozilla.org/en/dom/window.postmessage

6. Using Flash

This is the method seen from the IO component of YUI3, specifically visible http://developer.yahoo.com/yui/3/io/.

You can see more of the cross-domain proxy file specification in Adobe Developer connection: Ross-domain Policy, "File specifications," HTTP Headers blacklist.

From

1, Jsonp

The advantages of JSON:

1, based on plain text, cross-platform transmission is extremely simple;

2, JavaScript native support, background language almost all support;

3, lightweight data format, occupies very few characters, especially suitable for internet transmission;

4, readability is strong, although less than the XML so at a glance, but in a reasonable order after indentation is easy to identify;

5, easy to write and analysis, of course, if you want to know the data structure;

Like Google's Ajax search interface: http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=?&callback=?

Q=? This question mark indicates what you want to search for, and most importantly, the second callback=? This is the name of the callback function, which is named after its name, that is, the function name of your client-defined callback function is passed to the server, and the server returns a method with the name of the callback function you have defined. The retrieved JSON data is passed into this method to complete the callback. A bit wordy, or look at the implementation of the Code it:

<scripttype= "Text/javascript" >

Ways to add <script> tags

function Addscripttag (SRC) {

var script =document.createelement (' script ');

Script.setattribute ("type", "Text/javascript");

SCRIPT.SRC = src;

Document.body.appendChild (script);

}

Window.onload = function () {

Search Apple to pass the custom callback function name result into the callback parameter

Addscripttag ("Http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=apple&callback=result");

}

Custom callback function result

function result (data) {

We simply get the URL data from the first record in Apple search results

alert (Data.responsedata.results[0].unescapedurl);

}

</script>

Next we create a simple remote service that implements the same JSONP service as above. or using Web program A and program B to do the demo, this time we create a myservice.ashx file on program B.

MYSERVICE.ASHX Code for Program B:

1 public class Myservice:ihttphandler

2 {

3 Public Voidprocessrequest (HttpContext context)

4 {

5//Get callback function name

6 string callback =context. Request.querystring["Callback"];

7//json Data

8 String json = "{\" name\ ": \" Chopper\ ", \" sex\ ": \" man\ "}";

9

Ten context. Response.ContentType = "Application/json";

11//Output: callback function name (JSON data)

The context. Response.Write (Callback + "(" + JSON + ")");

13}

14

public bool IsReusable

16 {

+ Get

18 {

return false;

20}

21}

22}

Call in the sample code of program A:

1 <scripttype= "Text/javascript" >

2 function Addscripttag (SRC) {

3 var script =document.createelement (' script ');

4 Script.setattribute ("type", "Text/javascript");

5 script.src = src;

6 document.body.appendChild (script);

7}

8

9 window.onload = function () {

10//Call remote service

Addscripttag ("Http://localhost:20002/MyService.ashx?callback=person");

12

13}

14//callback function person

The function person (data) {

Alert (Data.name + "is a" + data.sex);

17}

</script>

The realization of jquery to Jsonp

The jquery framework also certainly supports JSONP, which can be used with the $.getjson (Url,[data],[callback]) method (see http://api.jquery.com/jQuery.getJSON/for details). Then we will modify the code of the program A, instead of the jquery Getjson method (The following example is useless to the service, so only write Getjson (Url,[callback])):

<script type= "Text/javascript" src= "Http://code.jquery.com/jquery-latest.js" ></script>

<script type= "Text/javascript" >

$.getjson ("http://localhost:20002/MyService.ashx?callback=?", function (data) {

Alert (Data.name + "is a A" + data.sex);

});

</script>

The result is the same, note that after the URL must be added a callback parameter, so that the Getjson method will know is to use JSONP way to access the service, callback the question mark is the internal automatically generated a callback function name. This function name you can debug a bit to see, such as jquery17207481773362960666_1332575486681.

<scripttype= "Text/javascript" src= "Http://code.jquery.com/jquery-latest.js" ></script>

<scripttype= "Text/javascript" >

$.ajax ({

URL: "http://localhost:20002/MyService.ashx?callback=?",

DataType: "Jsonp",

Jsonpcallback: "Person",

Success:function (data) {

Alert (Data.name + "is AA" + data.sex);

}

});

</script>

Yes, Jsonpcallback can specify our own callback method name person, and the remote service accepts that the value of the callback parameter is no longer an auto-generated callback name but a person. DataType is to specify that the remote service is accessed in jsonp manner.

jquery when dealing with Jsonp types of Ajax (or can not help to spit, although jquery also put Jsonp into Ajax, but in fact they are not a thing), automatically help you to generate a callback function and take the data out for the Success property method to invoke

1, Ajax and JSONP the two technologies in the invocation of the way "looks" very much like, the purpose is the same, is to request a URL, and then the server to return the data processed, so the jquery and ext and other frameworks have Jsonp as a form of Ajax encapsulation;

2, but Ajax and JSONP are actually different things in nature. The core of Ajax is to obtain non-page content through XMLHttpRequest, while the core of JSONP is dynamic add <script> tag to invoke the JS script provided by the server.

3, so that, in fact, the difference between Ajax and JSONP is not whether cross-domain, AJAX through the service-side proxy can be implemented across domains, JSONP itself does not exclude the same domain data acquisition.

4, there is, Jsonp is a way or non-mandatory protocol, like Ajax, it does not have to use JSON format to pass the data, if you want to, the string is OK, but this is not conducive to the use of JSONP to provide public services.

All in all, JSONP is not a special case of Ajax, even if the giant jquery, such as Jsonp encapsulated in Ajax, can not change a bit!

JS Cross-domain method

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.