Implementation of browser Cross-domain access solution in JS

Source: Internet
Author: User
Tags current time error handling json subdomain

Cross-Domain Concepts

Across the domain it is known that different addresses, different ports, different levels, and different protocols will form a cross-domain domain. For example: about. Www.111cn.net and www. Your domain name will form a cross-domain domain. summed up as long as the protocol, domain name, port has any difference, are treated as a different domain. Here are some examples of each of the two groups.

URL to indicate whether to allow traffic
http://www. your domain/a.js
http://www. Your domain/b.js the same domain name allows

http://www. your domain/lab/a.js
http://www. Your domain/script/b.js the same domain name under different folders allowed

http://www. Your domain name: 8000/a.js
http://www. Your domain name/b.js the same domain name, different ports are not allowed

http://www. your domain/a.js
Https://www. Your domain name/b.js the same domain name, different protocols do not allow
http://www. your domain/a.js
Http://60.32.92.74/b.js domain name and domain name corresponding IP not allowed

http://www. your domain/a.js
Http://about. Your domain name/b.js The primary domain is the same, the subdomain is different does not allow

http://www. your domain/a.js
http://your domain name/b.js the same domain name, different level two domain name (ditto) not allowed (cookie in this case also not allow access)

Http://www.hao123.com/a.js
http://www. Your domain/b.js different domain name does not allow
Solution to Cross-domain scenarios

In the last article, I wrote Window.postmessage, a cross-domain solution. Let me introduce a few more today.

Cors cross-domain resource sharing

As we all know, we used to cross the domain many times in a jsonp way, jsonp the way I described later. The following are the advantages of cors Cross-domain and jsonp across domains:

Compared with JSONP, Cors is no doubt more advanced, convenient and reliable.

1. JSONP can only implement get requests, while cors supports all types of HTTP requests.
2, the use of cors, developers can use the common XMLHttpRequest to initiate requests and access to data, compared to JSONP has better error handling.
3, Jsonp mainly by the old browser support, they often do not support cors, and most modern browsers have supported the Cors. [Low version IE7 below support, to support IE7 or to use JSONP way]
The use of cors

Cors should be configured at the back and rear.

1, first we look at the front.

Pure JS Ajax request.

<script type= "Text/javascript" >
var xhr = new XMLHttpRequest (); IE6 the following with the new ActiveXObject ("Microsoft.XMLHTTP"), the ability to judge.
Xhr.open ("Get", "/haorooms", true);
Xhr.send ();
</script>
The above haorooms is a relative path, and if we are going to use Cors, the relevant AJAX code might look like the following:

<script type= "Text/javascript" >
var xhr = new XMLHttpRequest ();//ie6 below with new ActiveXObject ("Microsoft.XMLHTTP"); ability to judge.
Xhr.open ("Get", "http://www. your domain name/cors", true);
Xhr.send ();
</script>
Of course, you can do it with jquery Ajax.

2, back-end or server-side configuration

Here we introduce the setup methods in Apache and PHP.

Apache:apache needs to use the Mod_headers module to activate the HTTP header setting, which is activated by default. All you need to do is add the following to the configuration of the < Directory, < Location>, < Files > or < virtualhost> in the Apache configuration file:

Header Set Access-control-allow-origin *
PHP: Just use the following code settings.

<?php
Header ("access-control-allow-origin:*");
The meaning of the above configuration is to allow any domain-initiated request to obtain data from the current server. Of course, there is a great danger that malicious sites may attack our servers via XSS. So we should try to be targeted to limit the security of the source, such as the following settings so that only www. your domain name domain can access the server's APIs across domains.

Access-control-allow-origin:http://www. Your domain name
Cross-Domain by JSONP

JSONP cross domains also need to be used in conjunction with the front and back. General back-end settings callback, front-end to the background interface to pass a callback can be.

For example, front-end code:

<script type= "Text/javascript" >
function DoSomething (jsondata) {
Processing the obtained JSON data
}
</script>
<script src= "http://your domain/data.php?callback=dosomething" ></script>
Background code:

<?php
$callback = $_get[' callback '];//get callback function name
$data = Array (' A ', ' B ', ' C ');//data to be returned
echo $callback. ' ('. Json_encode ($data). ') '; /output
?>
If you are using Ajax to Jsonp Cross-domain, I mentioned in an earlier article: http://www. your domain name/POST/JQUERY_AJAX_WG

/*
Short form, same effect
$.getjson ("url cross-domain address", {parameter) to pass the callback as an argument to the back end},
function (data) {
Structure processing
}, "Jsonp");
*/
$.ajax ({
Type: "Get",
URL: "Cross-domain Address",
DataType: "Jsonp",//The data type is JSONP
JSONP: "Callback",//server used to receive the parameters of the function name of the callback call "background accept what parameters, we will pass what parameters" we have the above set is callback
Success:function (data) {
Result processing
},
Error:function (data) {
Console.log (data);
}
});
To cross a subdomain by modifying document.domain

All we need to do is set up document.domain on two pages across the domain. The method of modifying Document.domain only applies to interactions between frameworks in different subdomains.

For example: 1. On the page http://www. Set document.domain in your domain/a.html

<iframe id = "iframe" src= "http://your domain/b.html" onload = "test ()" ></iframe>
<script type= "Text/javascript" >
Document.domain = ' your domain name ';//Set as the primary domain
function Test () {
Alert (document.getElementById (' iframe '). Contentwindow);//contentwindow the Window object for the child window to be obtained
}
</script>
2, in the page http://your domain name/b.html set document.domain

<script type= "Text/javascript" >
Document.domain = ' your domain name ';//In the IFRAME load this page also set Document.domain, make it the same as the main page document.domain
</script>
Using Window.name to cross domain

Principle:

The Window object has a Name property that has a feature: in the life cycle of a window (Windows), All the pages loaded in the window are shared by a window.name, each page has read and write permission to the Window.name, Window.name is persisted in all pages that a window has loaded.

Method:

If there are three pages.

A.com/app.html: Application page.
A.com/proxy.html: Agent file, is generally an HTML file without any content, need and apply the page under the same domain.
B.com/data.html: The page where the application page needs to get the data, can be called the data page.
1, in the Application page (a.com/app.html) to create an IFRAME, its SRC point to the data page (b.com/data.html).

The data page attaches the data to the window.name of the IFRAME, and the data.html code is as follows:

<script type= "Text/javascript" >
Window.name = ' I was there! '; Here is the data to be transmitted, the size of the general 2m,ie and Firefox can be large to 32M or so
Data formats can be customized, such as JSON, string
</script>
2, in the Application page (a.com/app.html) to monitor the onload incident in the IFRAME, this incident set this iframe to the SRC point to the local domain agent files (agent files and application pages in the same domain, so can communicate with each other).

app.html part of the code is as follows:

<script type= "Text/javascript" >
var state = 0,
iframe = document.createelement (' iframe '),
LOADFN = function () {
if (state = = 1) {
var data = Iframe.contentWindow.name; Reading data
alert (data); Pop ' I was there! '
else if (state = = 0) {
state = 1;
Iframe.contentWindow.location = "http://a.com/proxy.html"; Proxy file set by
}
};
IFRAME.SRC = ' http://b.com/data.html ';
if (iframe.attachevent) {
Iframe.attachevent (' onload ', LOADFN);
} else {
Iframe.onload = LOADFN;
}
Document.body.appendChild (IFRAME);
</script>

3, the acquisition of data after the destruction of the IFRAME, freeing memory, this also guarantees the security (not by other domain frame JS access).

<script type= "Text/javascript" >
Iframe.contentWindow.document.write (");
Iframe.contentWindow.close ();
Document.body.removeChild (IFRAME);
</script>


using the HTML5 Window.postmessage method to cross domain

About PostMessage

Window.postmessage is a HTML5 function, but support ie8+, if your site does not need to support IE6 and IE7, then you can use Window.postmessage. About Window.postmessage, a lot of friends say he can support Cross-domain, yes, Window.postmessage is the direct data transfer between client and client, which can be passed across domain or same domain.

Application Scenarios

I just give a simple application scenario, of course, this feature can be used in many places.

If you have a page, the page to get some of the user information, click to enter another page, the other page default is not to get the user information, you can through the window.postmessage part of the user information uploaded to this page. (Of course, you have to consider security and so on.) )

Code examples

Send a message:

A new window pops up
var domain = ' http://your domain name ';
var mypopup = window.open (domain
+ '/windowpostmessagelistener.html ', ' Mywindow ');

Send a message periodically
settimeout (function () {
var message = ' Current time is ' + (new Date (). GetTime ());
var message = {Name: "site", Sex: "Male"}; You can also pass some data here, obj and so on
Console.log (' The data passed is ' + message ');
Mypopup.postmessage (Message,domain);
},1000);

To delay, we generally use the timer settimeout delay and reuse.

Accepted pages

Listening for message feedback
Window.addeventlistener (' message ', function (event) {
if (event.origin!== ' http://your domain name ') return; This judge is not my domain to jump over the
Console.log (' Received response: ', event.data);
},false);
The following figure, accept the page to get the data

Enter image description here

If you are using an IFRAME, the code should write this:

Capturing IFRAME
var domain = ' http://your domain name ';
var iframe = document.getElementById (' Myiframe '). Contentwindow;

Send a message
settimeout (function () {
var message = ' Current time is ' + (new Date (). GetTime ());
var message = {Name: "site", Sex: "Male"}; You can also pass some data here, obj and so on
Console.log (' The data passed is: ' + message ');
Send the message and target URI
Iframe.postmessage (Message,domain);
},1000);

Accept Data

Responding to Events
Window.addeventlistener (' message ', function (event) {
if (event.origin!== ' http://your domain name ') return;
Console.log (' Message Received: ' + event.data,event);
Event.source.postMessage (' Holla back youngin! ', event.origin);
},false);

The code snippet above is a feedback message to the source, and the confirmation message has been received. The following are some of the more important event properties:

source– the message source, the sending window of the message/iframe.
origin– The URI of the message source, which may contain protocols, domain names, and ports, to validate the data source.
data– sends the data way sent to the receiving party.

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.