Brief analysis of js cross domain problem and comparison of advantages and disadvantages of solutions
- 2020-03-30 04:17:11
- OfStack
What is cross-domain?
Concept: as long as the protocol, domain name, and port are any different, it is treated as a different domain.
URL instructions Whether to allow communication
http://www.a.com/a.js
http://www.a.com/b.js Under the same domain name allow
http://www.a.com/lab/a.js
http://www.a.com/script/b.js Different folders under the same domain name allow
http://www.a.com:8000/a.js
http://www.a.com/b.js Same domain, different ports Don't allow
http://www.a.com/a.js
https://www.a.com/b.js Same domain, different protocol Don't allow
http://www.a.com/a.js
http://70.32.92.74/b.js Domain names correspond to domain names ip Don't allow
http://www.a.com/a.js
http://script.a.com/b.js The primary domain is the same, the subdomain is different Don't allow
http://www.a.com/a.js
http://a.com/b.js Same domain, different secondary domain (ibid.) Do not allow ( cookie In this case, access is not allowed.)
http://www.cnblogs.com/a.js
http://www.a.com/b.js Different domain name Don't allow
The differences between ports and protocols can only be resolved in the background.
Cross-domain resource sharing (CORS)
CROS (cross-origin Resource Sharing) cross-domain Resource Sharing defines how browsers and servers must communicate when accessing cross-domain resources. The basic idea behind CROS is to use custom HTTP headers to let the browser communicate with the server to determine whether the request or response should succeed or fail.
<script type="text/javascript">
var xhr = new XMLHttpRequest();
xhr.open("GET", "/trigkit4",true);
xhr.send();
</script>
The above trigkit4 is a relative path, and if we were to use CORS, the relevant Ajax code might look like this:
<script type="text/javascript">
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://segmentfault.com/u/trigkit4/",true);
xhr.send();
</script>
The difference between the code and the previous one is that the relative path is replaced by the absolute path of the other domain, which is the interface address that you want to access across the domain.
To solve the cross-domain problem, we can use the following methods:
Cross domain by jsonp
Now the question is, right? What is jsonp? Wikipedia defines JSONP (JSON with Padding) as a "usage mode" of JSON in the data format that allows web pages to request data from other domains.
JSONP, also known as stuffed JSON, is a new way of applying JSON, but it is simply JSON that is included in a function call, for example:
callback({"name","trigkit4"});
JSONP consists of two parts: the callback function and the data. The callback function is the function that should be called in the page when the response arrives, and the data is the JSON data passed into the callback function.
In js, it is not possible to directly request data on different domains using XMLHttpRequest. However, it is possible to introduce js script files on different domains on the page, and jsonp takes advantage of this feature. Such as:
<script type="text/javascript">
function dosomething(jsondata){
//Process the resulting json data
}
</script>
<script src="http://example.com/data.php?callback=dosomething"></script>
After the js file loads successfully, the function we specified in the url parameter will be executed, and the json data we need will be passed in as the parameter. Therefore, jsonp requires the corresponding page coordination on the server side.
<?php
$callback = $_GET['callback'];//You get the name of the callback function
$data = array('a','b','c');//The data to be returned is
echo $callback.'('.json_encode($data).')';//O < br / >
?>
Finally, the output is: dosomething(['a','b','c']);
If your page USES jquery, it's easy to jsonp with its encapsulated methods.
<script type="text/javascript">
$.getJSON('http://example.com/data.php?callback=?,function(jsondata)'){
//Process the resulting json data
});
</script>
Jquery automatically generates a global function to replace callback=? In the question mark, after the data will be automatically destroyed, is actually a temporary proxy function. The $.getjson method automatically determines whether it is cross-domain or not. Across domains, the jsonp callback function is called in the form of an asynchronously loaded js file.
Advantages and disadvantages of JSONP
CROS versus JSONP
Compared with JSONP, CORS is undoubtedly more advanced, convenient and reliable.
2. With CORS, developers can make requests and get data using plain XMLHttpRequest, which has better error handling than JSONP.
Browsers have a same-origin policy, and one of its limitations is that in the first method we said you can't request documents from different sources through ajax methods. The second limitation is that there is no js interaction between frameworks in different domains in the browser.
Different frameworks can get window objects, but not properties and methods. A page, for example, it is the address of the (link: http://www.example.com/a.html), there is an iframe in this page, it is SRC (link: http://example.com/b.html), obviously, this page is different domains with it inside the iframe framework, so we wouldn't be captured by writing javascript code in the page to get the things in the iframe:
<script type="text/javascript">
function test(){
var iframe = document.getElementById('ifame');
var win = document.contentWindow;//The window object in the iframe can be retrieved, but the properties and methods of the window object are nearly unavailable
var doc = win.document;//I can't get the document object
in the iframe
var name = win.name;//The name attribute of the window object
is also missing
}
</script>
<iframe id = "iframe" src="http://example.com/b.html" onload = "test()"></iframe>
This time of the document. The domain can come in handy, as long as we put (link: http://www.example.com/a.html) and (link: http://example.com/b.html) this two page document. The domain are set to the same domain name. However, it is important to note that the setting of document.domain is limited. We can only set document.domain as a parent domain of itself or higher, and the primary domain must be the same.
1. The page (link: http://www.example.com/a.html) set in the document. The domain:
<iframe id = "iframe" src="http://example.com/b.html" onload = "test()"></iframe>
<script type="text/javascript">
document.domain = 'example.com';//Set to the primary field
function test(){
alert(document.getElementById('iframe').contentWindow);//ContentWindow gets the window object of the child window
}
</script>
2. The page (link: http://example.com/b.html) has also set up the document. The domain:
<script type="text/javascript">
document.domain = 'example.com';//Loading this page in the iframe also sets the document.domain to be the same
as the document.domain on the main page
</script>
The method that modifies document.domain only works for interactions between frameworks of different subdomains.