Deep analysis of JavaScript cross-domain problems _javascript skills

Source: Internet
Author: User
Tags setinterval

What is a cross domain?

Suppose a.com/get.html need to get b.com/ Data.html in the data, and here a.com and B.Com is not the same server, this is Cross-domain Cross-domain will involve JavaScript homology strategy, simply to protect the site security, not by the alien (not homologous) Server JS Modify this site content.
Refer to a table to see what conditions are causing the cross-cause:

But sometimes we do need to do this, so what are the ways we do it?

1, JsonP

The reference to JSONP cannot be mentioned without reference to the cross domain first. JSONP is actually the abbreviation for Javacscript Object notation with padding, which can be understood as JSON-formatted data populated with content.
Because the above declares the callback and invokes the data.js of the Outland B.Com, the Data.js calls:
Callback ({msg: "Tqtan"});
This will call local callback () when invoking JS in Outland to implement data transfer.
The above is just a simple cross-domain, and we see the real use of jquery.

The Ajax in jquery pulls out data from the Outland in two ways:

1, $.getjson ()

This method is simple and rough, requesting the Outland JSON.

Copy Code code as follows:

$.getjson ("http://b.com/dataServlet?callback=?", function (data) {
Console.log (DATA.MSG);
});

Assuming that the above request accesses the servlet page under B.Com, the passed parameter to Callback=?,jquery automatically generates a string fill placeholder? such as callback=jquery17207481773362960666_ 1332575486681. This declares a unique identifier with the server, and the server only needs to return JSON-formatted data with this callback value, for example:

Copy Code code as follows:

Dataservlet.java
String callback = Req.getparameter ("callback");
PrintWriter out = Resp.getwriter ();
Out.print (callback+ "(' msg ', ' Tqtan ')");

This will enable you to successfully obtain data from a server that is not homologous.

2, $.ajax ()

The implementation principle is the same as above, but you can customize more links.

$.ajax ({
URL: ' Http://b.com/dataServlet?words=hi ',
dataType: ' Jsonp ',
jsonp: ' Jsoncallback '
, Jsoncallback: ' Tqtan ',
success:function (data) {
console.log (data.msg);
},
error:function (e) {
Console.log (e);
}
});

You can customize the name of the callback and change it to ' Tqtan ', where you can also pass the value Words=hi.
Note that the JSONP format can only request a server in get form.

2, Document.domain

This method applies only to the same primary domain and to different cross-domain domains.
That is, the cross-domain problem of get.a.com and data.a.com, the solution is simple:
If get.a.com/get.html need to get data.a.com/data.html data, first insert a iframe,src point in the get.html to the data.a.com/ Data.html, then write document.domain= ' a.com ' in data.html and manipulate the contents of data.html.

Get.html
var iframe = document.createlement ("iframe");
Iframe.src= "http://data.a.com/data.html";
Iframe.style.display= "None";
Document.body.appendChild (IFRAME);
Document.domain = ' a.com ';
Iframe.onload = function () {
var otherdocument = iframe.contentdocument | | iframe.contentWindow.document;
Otherdocument is another page of document
//do whatever you want.
};
data.html
document.domain = ' a.com ';

3, URL Hash

You can also use the hash of the URL to implement Cross-domain. Hash is the content behind the url#, such as http://targetkiller.net/index.html, where #data is hash. How to use this to achieve cross-domain?

Or that example, a.com/get.html need to get b.com/data.html, first in get.html to establish a iframe,src or point to data.html, followed by the hash value to implement the argument. The other end data.html responds to the hash obtained, creates a iframe,src point to a.com/proxy.html, and adds the response data to the hash. After that, a.com/proxy.html only needs to modify the hash of the get.html in the same a.com parent domain. Finally, how do we get the data? Only need to write a timer in get.html setinterval, regular monitoring There is no new hash can be.

See here, you may feel the beginning of chaos, a few questions:

1.proxy.html's role?
Because get.html and data.html not on a domain, so can not modify the Location.hash value, so the use of proxy.html, first jump to find a proxy page, and then through the Parent.location.hash, that is, to modify the father, so that the son (get.html) also have to to the response.
A.com/get.html

var iframe = document.createelement (' iframe ');
IFRAME.SRC = ' http://a.com/get.html#data ';
Iframe.style.display = ' None ';
Document.body.appendChild (IFRAME);
Periodic detection hash update
function Gethash () {
var data = Location.hash? location.hash.substring (1): ';
Console.log (data);
}
var hashint = setinterval (function () {Gethash ()}, 1000);
a.com/proxy.html
Parent.location.hash = self.location.hash.substring (1);
B.com/data.html
//Simulate a simple parameter processing operation
if (location.hash) {
var data = Location.hash;
Dosth (data);
}
function Dosth (data) {
Console.log ("from a.com:" +data);
var msg = "Hello i am b.com";
var iframe = document.createelement (' iframe ');
IFRAME.SRC = "http://a.com/proxy.html#" +MSG;
Iframe.style.display = ' None ';
Document.body.appendChild (iframe);
}

4, Window.name

This is a clever way to refer to the explanation of the center of the circle, where the name value still exists after a different page (or even a different domain name) is loaded, and can support very long name values (2MB). The
example remains the same, and it also requires a proxy page.
a.com/get.html request b.com/data.html, first get.html create a iframe,src point to data.html, then listen for the onload event of the IFRAME. At the same time, set the Window.name = data in the data.html and assign the Window.name value. Then the onload incident immediately after the IFrame jumped to the local a.com/proxy.html. So Window.name is shared to the SRC for proxy.html to find an IFRAME, then, is the same homology between the matter of getting value.
A.com/get.html

var state = 0,
iframe = document.createelement (' iframe '),
iframe.src = ' http://b.com/data.html ';
Iframe.style.display = ' None ';
LOADFN = function () {
if (state = = 1) {
var data = Iframe.contentWindow.name;
Console.log (data);
} else if (state = = 0) {state
= 1;
Skip to proxy.html
iframe.contentWindow.location = "http://a.com/proxy.html";
}
;
if (iframe.attachevent) {
iframe.attachevent (' onload ', LOADFN);
} else {
iframe.onload = LOADFN;
}
Document.body.appendChild (IFRAME);
a.com/proxy.html
//proxy.html operations are mainly to delete the get.html iframe, to avoid security problems occur
Iframe.contentWindow.document.write (" );
Iframe.contentWindow.close ();
Document.body.removeChild (IFRAME);
b.com/data.html
var data = "Hello,tqtan";
Window.name = data;

5, PostMessage ()

The new method of HTML5 PostMessage () gracefully solves the Cross-domain and is also very easy to understand.
The sender invokes the PostMessage () content and the receiver listens for OnMessage to accept the content.
Suppose the sender is a.com/send.html and the receiver is b.com/receive.html.
A.com/send.html

var iframe = document.createelement ("iframe");
IFRAME.SRC = "http://b.com/receive.html";
Document.body.appendChild (IFRAME);
Iframe.contentWindow.postMessage ("Hello", "http://b.com");
b.com/receive.html
window.addeventlistener (' message ', function (event) {
//) to determine the source address via the Origin attribute
( Event.origin = = ' http://a.com ') {
console.log (event.data);
Console.log (Event.source);//Send source window value
}
, False);

6, CORS (Backstage implementation)

The above 5 points are a cross-domain implementation of the front-end, but background involvement makes it easier to resolve across domains, that is, with Cors.
Cors is the abbreviation of Cross-origin Resource sharing, that is, cross domain resource sharing. How awesome is it? Previously said JSONP can only get requests, but cors can accept all types of HTTP requests, yet cors is supported only by modern browsers.
How to use it? Front end only need to send ordinary Ajax request, pay attention to detect cors support degree. Reference from Shiyute.

function Createcorsrequest (method, url) {
var xhr = new XMLHttpRequest ();
if ("Withcredentials" in xhr) {//
at this point support cors condition
//Check that XMLHttpRequest object has "Withcredentials" attribute
//" Withcredentials "only exists in the XMLHTTPRequest2 object
xhr.open (method, URL, True);
}
else if (typeof!= "undefined") {
//otherwise check to see if support for XDOMAINREQUEST,IE8 and IE9 support
//Xdomainrequest only exists in IE, Is the way IE is used to support cors requests
XHR = new Xdomainrequest ();
Xhr.open (method, url);
else {
//Otherwise, the browser does not support cors
xhr = null;
}
return xhr;
}
var xhr = createcorsrequest (' Get ', url);
if (!XHR) {
throw new Error (' CORS not supported ');
}

At the same time, the server side only needs to set the Access-control-allow-origin header.

In Java you just need to set

Copy Code code as follows:

Response.setheader ("Access-control-allow-origin", "*");

For security, you can also change the * to a specific domain name, such as A.com.

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.