Multiple methods for implementing cross-origin in js,

Source: Internet
Author: User

Multiple methods for implementing cross-origin in js,

Starting from the domain

Domain:The domain is the security boundary of the WIN2K network system. We know that the most basic unit of a computer network is "Domain", which is not unique to WIN2K, but the Active Directory can run through one or more domains. On an independent computer, the domain refers to the computer itself. A domain can be distributed across multiple physical locations. At the same time, a physical location can be divided into different network segments for different domains, each domain has its own security policy and its trust relationship with other domains. When multiple domains are connected by a trust relationship, the Active Directory can be shared by multiple trust domain domains.
Domain tree:The domain tree consists of multiple domains that share the same table structure and configuration to form a continuous namespace. The fields in the tree are connected by trust relationships. The active directory contains one or more domain trees. The domains in the domain tree are connected by two-way convertible trust relationships. Because these trust relationships are bidirectional and pass-able, newly created domains in the domain tree or forest can immediately establish trust relationships with each other in the domain tree or forest. These trust relationships allow a single login process to authenticate users on all domains in the domain tree or forest, however, this does not necessarily mean that Authenticated Users have the same rights and permissions in all domains in the domain tree. Because the domain is a security limit, you must assign the corresponding rights and permissions to the user on the basis of each domain.
The deeper the domain hierarchy in the domain tree, the lower the level. A "." represents a level.
For example, the domain zhidao.baidu.com (Baidu Knows) is lower than that of baidu.com (Baidu) because it has two levels, while baidu.com has only one layer.

What is cross-origin?

By default, an XHR object can only access resources in the same domain as the page containing it. This security policy can prevent some malicious behaviors. However, the realization of reasonable cross-origin requests is also crucial to the development of some browser applications.
As long as the Protocol, domain name, and port are different, they are treated as different domains.

For example, sending an ajax request to the following page on the http://www.a.com/a.js page, the following are the request results and descriptions

Different ports and protocols can only be solved through the background. What we need to solve is the problem of different domain names.

How to cross-Origin

(1) CORS (Cross-Origin Resource Sharing)

1. CORS (Cross-Origin Resource Sharing) is a W3C working draft that defines how browsers and servers communicate when Cross-source resources must be accessed. The basic idea behind CORS is to use a custom HTTP header to allow the browser to communicate with the server and decide whether the request or response should succeed or fail.
2. Implementing this function is very simple. You only need to send a response header by the server.

Browser support:

  • IE 8 +
  • Firefox 3.5 +
  • Opera 12 +
  • Safari 4 +
  • Chrome 3 +

Suppose that our page or application is already on the http://www.a.com/, and we intend to extract data from the http://www. B .com request. In general, if we directly use AJAX for the request, it will fail, and the browser will return an error.
With CORS, The http://www. B .com can allow requests from the http://www.a.com by adding only one header.
The following is the setting in php. "*" indicates that any domain is allowed to submit requests to our server:

header{"Access-Control-Allow-Origin: *"}

CORS compatibility

Function createCORSRequest (method, url) {var xhr = new XMLHttpRequest (); // non-IE browser if ("withCredentials" in xhr) {xhr. open (method, url, true); // IE browser} else if (typeof XDomainRequest! = "Undefined") {vxhr = new XDomainRequest (); xhr. open (method, url);} else {xhr = null;} return xhr;} var request = createCORSRequest ("get", "http://www.somewhere-else.com/page/"); if (request) {request. onload = function () {// request. responseText for processing}; request. send ();}

(2) JSONP (JSON with Padding filling JSON or parameter JSON)

In js, although we cannot directly use XMLHttpRequest to request data in different domains, it is okay to introduce js script files in different domains on the page, jsonp is implemented using this feature.

JSONP consists of the callback function and data. The callback function is the function that should be called on the page when the response arrives, and the data is the JSON data passed into the callback function.

For example:

<Script type = "text/javascript"> function dosomething (jsondata) {// process the obtained json data} </script> <script src = "http://example.com/data.php? Callback = dosomething "> </script>

First, the first script tag defines a function for data processing;
Then the second script label to load a js file, the http://example.com/data.php is the address of the data, but because it is introduced as js, so the http://example.com/data.php returned must be a Javascript file that can be executed;
After the js file is loaded successfully, the function specified in the url parameter will be executed, and the json data we need will be passed in as the parameter. So php should be like this.

<? Php $ callback = $ _ GET ['callback']; // GET the callback function name $ data = array ('A', 'B', 'C '); // echo $ callback. '('. json_encode ($ data ). ')'; // output?>

Finally, the output result is: dosomething (['A', 'B', 'C']);
From the above, we can see that jsonp requires the server-side page to cooperate accordingly.

Advantages and disadvantages of JSONP
Advantages:

It has better compatibility and can run in older Browsers without the support of XMLHttpRequest or ActiveX;
Ability to directly access response text and support two-way communication between browsers and servers
Disadvantages:

JSONP loads code execution from other domains. If other domains are not secure, some malicious code may be included in the response. In this case, there is no way to investigate the issue except for completely giving up the JSONP call. Therefore, when using a Web service that is not operated and maintained by yourself, you must ensure its security and reliability.
It only supports GET requests, but does not support POST and other types of HTTP requests. It only supports cross-origin HTTP requests. It cannot solve the problem of JavaScript calls between two pages in different domains.
(3) window. name

The window object has a name attribute, which has a feature: In the lifecycle of a window, all pages loaded by the window share a window. name, each page on the window. all names have read and write permissions, window. name is permanently stored in all pages loaded by a window and will not be reset due to loading of the new page.

There are three pages:

A.com/app.html:application page.
A.com/proxy.html:the proxy file is generally an HTML file without any content, and its contents and application pages are in the same domain.
B .com/data.html:the page where data is obtained from the application page, which can be called the data page.

App.html

<Iframe src = "B .com/data.html" id = "iframe"> </iframe> <script> var iframe = document. getElementById ("iframe"); iframe. src = "a.com/proxy.html"; // This is an iframe page with the same source as a.com/app.html. onload = function () {var data = iframe. contentWindow. name; // get data} </script>

Data.html

<Script> // The data to be transmitted. The data size is generally 2 MB. The size of IE and firefox can be about 32 MB. // the data format can be customized, such as json and string window. name = "data" </script>

The first address of iframe is B .com/data.html, so that the registrant namedata can be obtained;
However, iframeis not the same as app.html, and app.html cannot obtain data. Therefore, the link of iframe is redirected to the proxy page a.com/proxy.html. now app.html is the same as iframe.

Note: iframe is sent from B .com/data.html#to a.com/proxy.html, And the valuevalue of the specified nameis unchanged.

Destroy the iframe after obtaining the data and release the memory. This ensures security (not accessed by frame js in other domains)

<script type="text/javascript"> iframe.contentWindow.document.write(''); iframe.contentWindow.close(); document.body.removeChild(iframe);</script>

(4) document. domain + iframe

For examples with the same primary domain and different subdomains, you can set document. domain.
You can set document in the http://www.a.com/a.html and http://script.a.com/ B .html files. domain = 'a.com', then create an iframe in the a.html file to control the contentDocument of iframe, so that the two js files can "interact.
Http://www.a.com/a.html page

<iframe src="http://script.a.com/b.html" frameborder="0"></iframe><script> document.domain = 'a.com';</script>

Http://script.a.com/ B .htmlpage

<script> document.domain = 'a.com';</script>

In this way, the two pages can access various attributes and objects through js.

The settings of document. domain are restricted., We can only set document. domain to its parent domain or a higher level, and the primary domain must be the same. For example, the document of a document in a. B .example.com. domain can be set to either a. B .example.com, B .example.com, or example.com, but it cannot be set to c.a. B .example.com because it is a subdomain of the current domain and cannot be set to baidu.com because the primary domain is different.

(5) HTML5 window. postMessage

Window. the postMessage (message, targetOrigin) method is a new feature of html5. it can be used to send messages to other window objects, whether the window object is of the same or different origins, currently, IE8 +, FireFox, Chrome, Opera, and other browsers all support windows. postMessage method.
Window. postMessage allows two windows/frames to send data messages across domains. In essence, window. postMessage is a cross-domain Ajax without server gaskers.

Usage:
OtherWindow. postMessage (message, targetOrigin );

  • OtherWindow: Reference to the window on the receiving information page. It can be the contentWindow attribute of iframe on the page, the return value of window. + open, and the value obtained from window. frames through name or subscript.
  • Message: The data to be sent, of the string type.
  • TargetOrigin: used to restrict otherWindow. "*" indicates no restriction.

Data sender
A.com/index.html code:

<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 '; // set the receiver's domain, * indicates that ifr is not limited. contentWindow. postMessage ('I was there! ', TargetOrigin) ;}; </script>

Data receiving end
B .com/index.html code:

<Script type = "text/javascript"> window. addEventListener ('message', function (event) {// determine the message source address if (event. origin = 'HTTP: // a.com ') {alert (event. data); // The "I was there! "Alert (event. source); // reference the window object in a.comw.index.html // However, due to the same-origin policy, event. source cannot access window objects }}, false); </script>

The above is a variety of methods for implementing cross-origin in js, hoping to help you learn.

Articles you may be interested in:
  • How to implement cross-origin access using jsonp in jquery
  • Use of ajax jsonp for cross-origin requests
  • Jquery $. getJSON () Cross-origin request
  • JS cross-origin Summary
  • In-depth introduction to js iframe cross-origin access (same main domain/non-main domain)
  • Jquery ajax jsonp cross-origin call instance code
  • Implementation of jquery's ajax and getJson cross-origin acquisition of json data
  • Use jQuery and JSONP to easily solve cross-origin access problems
  • Use jsonp to perfectly solve cross-origin problems

Related Article

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.