Cross-Domain common solutions

Source: Internet
Author: User

due to security concerns, HTML's same-origin policy does not allow JavaScript to cross-domain operations, but as the web-side functions more and more, the demand for cross-domain gradually increased, thus creating a lot of solutions to cross-domain methods, through the network search and data query, The main more common solutions are the following:     First, set Document.domain
    • Principle: Different sub-domains under the same primary domain page, by setting document.domain to let them the same domain;
    • Limitations: This method is only applicable with cross-subdomain, and is still not feasible for cross-parent domain names and needs to be loaded into the IFRAME page.
1 //URL Http://bentos.com/foo2 varIFR = document.createelement (' iframe ');3IFR.SRC = ' Http://b.bentos.com/foo '; 4Ifr.onload =function(){5     varIfrdoc = Ifr.contentdocument | |ifr.contentWindow.document;6Ifrdoc.getelementsbyid ("foo"). InnerHTML);7                         };8 9Ifr.style.display = ' None ';TenDocument.body.appendChild (IFR);

The URL for the above code http://bentos.com/foo is that it http://b.bentos.com/bar requires document.domain DOM access to the latter to set the first level

// URL Http://b.bentos.com/bar 1 document.domain = ' bentos.com '

// URL: http://b.bentos.com/foovar data = { foo: ‘bar‘, bar: ‘foo‘};callback(data);


Second, Jsop
    • principle: <SCRIPT> is a function that can be cross-domain, and can directly callback the current script in a cross-domain script.
    • restriction: you need to create a DOM object and add it to the DOM tree, only for get method
    •  1  //   Url:http://b.bentos.com/foo  2  Span style= "color: #0000ff;" >var  data = { 3  foo: ' Bar ' ,  4  bar: ' foo ' 5                    };
      6  callback (data); 
    • 1 // Url:http://bentos.com/foo 2 var function (data) {3     // processing data from cross-domain requests 4                              }; 5 var script = $ (' <script> ', {src: ' Http://b.bentos.com/bar '}); 6 $ (' body '). Append (script);

Three Navigation Object
    • Principle: An IFRAME is a navigator shared object that uses it to pass information
    • Requirements: IE6/7

Some people notice a loophole in IE6/7: iframe the window.navigator objects between are shared. We can use it as a Messengerto pass information through it. For example, a simple delegate:

 1 //  bentos.com  2 Navigation.ondata () { 3 //  data arrives processing function  4 5 typeof  navigation.getdata = = = ' function ' 6 | |  Navigation.getdata ()  //  baidu.com  navigation.getdata = function   () {$.get ( '/path/under/baidu.com ' ). Success ( /span>function   (data) { typeof  Navigation.ondata = = = ' function ' | |  Navigation.ondata (data)});  

document.navigator window.name also shared with all pages of the current window. It can also be used to pass information.

Iv. Window.postmessage

    • Principle: HTML5 allow messages to be sent between windows
    • Limitations: Browsers need to support HTML5 to get window handles before they can communicate with each other

This is a secure cross-domain communication method and postMessage(message,targetOrigin) is also a feature introduced by HTML5. You can send a message to any window, whether it is homologous or not. The second argument can be * but if you set a URL but do not match it, the event will not be distributed. Look at an ordinary way of using it:

1 //Url:http://bentos.com/foo2 varWin = window.open (' Http://b.com/bar ');3Win.postmessage (' Hello, bar! ', ' http://b.com '); 4 5 6 7 //Url:http://baidu.com/bar8Window.addeventlistener (' message ',function(event) {9 Console.log (event.data);Ten});

Note IE8 and versions smaller than IE8 are not supported addEventListener and need attachEvent to be used to listen for events. See also: This:attachevent, AddEventListener, onclick in event handling

Five,Cross-domain resource sharing (CORS)
    • Rationale: Access-Control-Allow-Origin After the server sets the HTTP response header, the browser will allow cross-domain requests
    • Limitations: Browsers need to support HTML5, can support Post,put and other methods

For example, http://a.com from the http://b.com data you want to access, typically chrome will complain about cross-domain requests:

1 XMLHttpRequest cannot load http://B.Com. No ' Access-control-allow-origin ' header is present on the requested resource. Origin ' http://a.com ' is therefore not allowed access.

The reason for the error is that the Access-Control-Allow-Origin requested resource is not set, so we b.com can set the response header field in the server:

1 access-control-allow-origin: *              # allows all domain names to be accessed, or 2 access-control-allow-origin:http: // a.com   # only allows access to all domain names

in HTML5 before coming out, cross-domain adoption of common methods for Jsonp,jquery also gives support. It is important to note that it is only Hackand does not produce additional security issues. Because Jsonp is going to get the data successfully, it needs to mate with the server on which the resource resides, such as where the server needs to voluntarily callback an appropriate function, so the server still has the ability to control cross-domain access to the resource.

The cross-domain approach is also to use the CORS header field provided by window.postMessage HTML5 and to support HTTP methods such as post, put, and to solve cross-domain problems from a mechanism. It is important to Access-Control-Allow-Origin Note that the header field is set by the server where the resource is located, and the responsibility for access control is still on the server that provides the resource, which is the same as JSONP.

Cross-Domain common solutions

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.