For security reasons, HTML’s same-origin policy does not allow JavaScript to operate across domains, but as Web apps become more and more powerful, cross-domain requirements spawn numerous cross-domain practices. Even the HTML5 standard gives an official cross-domain approach, which is also a recent need to deal with interviews, with an article summarizing the various cross-domain approaches that already exist.
After some research, finally make clear the basic practice of cross – domain. These methods can be broadly divided into two categories:
- One is Hack, like passing
title
.navigation
JSONP is arguably one of the best hacks. - The other is HTML5 support, one is
Access-Control-Allow-Origin
The response header, one iswindow.postMessage
.
Set up the document. The domain
- Principle: You can set pages under the same master domain name and different subdomain names
document.domain
Let them be codomain - Limitations: Co-domain documents provide interoperation between pages and need to load iframe pages
Pages under the following domains are interoperable through document.domain: http://a.com/foo, http://b.a.com/bar, http://c.a.com/bar. However, page interoperation can only be carried out in the way of page nesting, such as the common iframe way to complete page nesting:
// URL http://a.com/foo
var ifr = document.createElement('iframe');
ifr.src = 'http://b.a.com/bar';
ifr.onload = function(){
var ifrdoc = ifr.contentDocument || ifr.contentWindow.document;
ifrdoc.getElementsById("foo").innerHTML);
};
ifr.style.display = 'none';
document.body.appendChild(ifr);
Copy the code
The above URL is http://a.com/foo, and its DOM access to http://b.a.com/bar requires the latter to set document.domain one level up:
// URL http://b.a.com/bar
document.domain = 'a.com'
Copy the code
Document.domain can only be set from subdomain to primary domain. Setting down to other domains is not allowed.
Uncaught DOMException: Failed to set the 'domain' property on 'Document': 'baidu.com' is not a suffix of 'b.a.com'
Copy the code
There are SRC tags
- Principle: All have
src
Attribute HTML tags are cross-domain, including.