Home  >  Article  >  Web Front-end  >  How to use javascript to achieve cross-domain? Summarize several ways of cross-domain JavaScript

How to use javascript to achieve cross-domain? Summarize several ways of cross-domain JavaScript

伊谢尔伦
伊谢尔伦Original
2017-06-02 10:12:031755browse

Start with 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 a "domain". This is not unique to WIN2K, but Active Directory can run through one or more domains. On an independent computer, a domain refers to the computer itself. A domain can be distributed in multiple physical locations. At the same time, a physical location can be divided into different network segments into different domains. Each domain has its own security policy and its relationship with Trust relationships with other domains. When multiple domains are connected through trust relationships, Active Directory can be shared by multiple trust domains
Domain tree:The domain tree consists of multiple domains, which are shared The same table structure and configuration form a continuous name space. Domains in a tree are connected through trust relationships, and Active Directory contains one or more domain trees. Domains in the domain tree are connected through bidirectional transitive trust relationships. Because these trust relationships are bidirectional and transitive, a newly created domain in a domain tree or forest can immediately establish a trust relationship with every other domain in the domain tree or forest. These trust relationships allow a single sign-on process that authenticates users across all domains in a domain tree or forest, but this does not necessarily mean that an authenticated user has the same rights and permissions across all domains in the domain tree. Because domains are security boundaries, users must be assigned appropriate rights and permissions on a per-domain basis.
The deeper the domain level in the domain tree, the lower the level. A "." represents a level.
For example, the domain zhidao.baidu.com (known to Baidu) is of a lower level than the domain baidu.com (Baidu) because it has two levels of relationships, while baidu.com has only one level.

What is cross-domain

By default, an XHR object can only access resources in the same domain as the page that contains it . This security strategy can prevent certain malicious behaviors. However, implementing reasonable cross-origin requests is also crucial for developing certain browser applications.
As long as there is any difference in the protocol, domain name, or port, they will be regarded as different domains. The differences in ports and protocols can only be resolved through the background. What we have to solve is the problem of different domain names

How to cross domains

(1) CORS( Cross-Origin Resource Sharing, Cross-Origin Resource Sharing)

1.CORS (Cross-Origin Resource Sharing, Cross-Origin Resource Sharing) is a W3C working draft that defines the How should the browser and server communicate when using cross-origin resources? The basic idea behind CORS is to use custom HTTP headers to allow the browser to communicate with the server to determine whether the request or response should succeed or fail.
2. Implementing this function is very simple, just send a response header by the server.

Browser support:

  • IE 8+

  • Firefox 3.5+

  • ##Opera 12+

  • ##Safari 4+

  • Chrome 3+

  • Assume that our page or application is already on a.com, and we plan to start from b. com request to extract data. Normally, if we use AJAX directly to request, the request will fail and the browser will return an error.
With CORS, b.com only needs to add a header to allow requests from .a.com.

The following is the setting using php. The "*" sign indicates that any domain is allowed to submit requests to our server:

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

CORS compatibility writing method

 function createCORSRequest(method, url){
 var xhr = new XMLHttpRequest();
 //非IE浏览器
 if ("withCredentials" in xhr){
 xhr.open(method, url, true);
 //IE浏览器
 } else if (typeof XDomainRequest != "undefined"){
 vxhr = new XDomainRequest();
 xhr.open(method, url);
 } else {
 xhr = null;
 }
 return xhr;
 }
 var request = createCORSRequest("get", "http://example.com/page/");
 if (request){
 request.onload = function(){
 //对request.responseText 进行处理
 };
 request.send();
 }

(2) JSONP (JSON with Padding filled JSON or parameterized JSON)In js, although we cannot directly use XMLHttpRequest to request data on different domains, but when It is possible to introduce js script files from different domains on the page. jsonp uses this feature to implement

JSONP consists of two parts: callback function and data. The callback function is the function that should be called in the page when the response comes, and the data is the JSON data passed into the callback function.

For example:

<script type="text/javascript">
 function dosomething(jsondata){
 //处理获得的json数据
 }
</script>
<script src="http://example.com/data.php?callback=dosomething"></script>

First, the first script note defines a function that processes data;

Then the second script tag loads a js file, data.php is where the data is address, but because it is introduced as js, data.php must return an executable js file; finally, after the js file is successfully loaded, the function we specified in the url parameter will be executed, and the functions we need will be json data is passed in as a parameter. So php should be like this

<?php
$callback = $_GET[&#39;callback&#39;];//得到回调函数名
$data = array(&#39;a&#39;,&#39;b&#39;,&#39;c&#39;);//要返回的数据
echo $callback.&#39;(&#39;.json_encode($data).&#39;)&#39;;//输出
?>

Finally, the output result is: dosomething(['a','b','c']);

It can be seen from the above that jsonp requires a server-side page cooperate accordingly.


Advantages and disadvantages of JSONP
Advantages:

它的兼容性更好,在更加古老的浏览器中都可以运行,不需要XMLHttpRequest或ActiveX的支持;
能够直接访问响应文本,支持在浏览器与服务器之间双向通信
缺点:

JSONP 是从其他域中加载代码执行。如果其他域不安全,很可能会在响应中夹带一些恶意代码,而此时除了完全放弃JSONP 调用之外,没有办法追究。因此在使用不是你自己运维的Web 服务时,一定得保证它安全可靠。
它只支持GET请求而不支持POST等其它类型的HTTP请求;它只支持跨域HTTP请求这种情况,不能解决不同域的两个页面之间如何进行JavaScript调用的问题。
(三) window.name

window对象有个name属性,该属性有个特征:即在一个窗口(window)的生命周期内,窗口载入的所有的页面都是共享一个window.name的,每个页面对window.name都有读写的权限,window.name是持久存在一个窗口载入过的所有页面中的,并不会因新页面的载入而进行重置。

这里有三个页面:

a.com/app.html:应用页面。
a.com/proxy.html:代理文件,一般是一个没有任何内容的html文件,需要和应用页面在同一域下。
b.com/data.html:应用页面需要获取数据的页面,可称为数据页面。

app.html

<iframe src="b.com/data.html" id="iframe"></iframe>
<script>
 var iframe = document.getElementById("iframe");
 iframe.src = "a.com/proxy.html";//这是一个与a.com/app.html同源的页面
 iframe.onload = function(){
 var data = iframe.contentWindow.name; //取到数据
 }
</script>

data.html

<script>
 // 这里是要传输的数据,大小一般为2M,IE和firefox下可以大至32M左右
 // 数据格式可以自定义,如json、字符串
 window.name = "数据"
</script>

iframe首先的地址是b.com/data.html,所以能取到window.name数据;
但是iframe现在跟app.html并不同源,app.html无法获取到数据,所以又将iframe的链接跳转至a.com/proxy.html这个代理页面,现在app.html跟iframe就同源了。

注意:iframe由b.com/data.html跳转到a.com/proxy.html页面,window.name的value是不变的

获取数据以后销毁这个iframe,释放内存;这也保证了安全(不被其他域frame js访问)

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

(四) document.domain + iframe

对于主域相同而子域不同的例子,可以通过设置document.domain的办法来解决。
具体的做法是可以在a.com/a.html 和script.a.com/b.html 两个文件中分别设置document.domain = 'a.com',然后通过a.html文件中创建一个iframe,去控制iframe的contentDocument,这样两个js文件之间就可以“交互”了。
a.com/a.html页面

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

script.a.com/b.html页面

<script>
 document.domain = &#39;a.com&#39;;
</script>

这样俩个页面就可以通过js相互访问各种属性和对象了。

document.domain的设置是有限制的,我们只能把document.domain设置成自身或更高一级的父域,且主域必须相同。例如:a.b.example.com 中某个文档的document.domain 可以设成a.b.example.com、b.example.com 、example.com中的任意一个,但是不可以设成 c.a.b.example.com,因为这是当前域的子域,也不可以设成baidu.com,因为主域已经不相同了。

(五) HTML5的window.postMessage

window.postMessage(message,targetOrigin) 方法是html5新引进的特性,可以使用它来向其它的window对象发送消息,无论这个window对象是属于同源或不同源,目前IE8+、FireFox、Chrome、Opera等浏览器都已经支持window.postMessage方法。
window.postMessage允许两个窗口/帧之间跨域发送数据消息。从本质上讲,window.postMessage是一个跨域的无服务器垫片的Ajax。

用法:
otherWindow.postMessage(message, targetOrigin);

  • otherWindow: 对接收信息页面的window的引用。可以是页面中iframe的contentWindow属性;window.+open的返回值;通过name或下标从window.frames取到的值。

  • message: 所要发送的数据,string类型。

  • targetOrigin: 用于限制otherWindow,“*”表示不作限制

数据发送端a.com/index.html中的代码:

<iframe id="ifr" src="b.com/index.html"></iframe>
<script type="text/javascript">
window.onload = function() {
 var ifr = document.getElementById(&#39;ifr&#39;);
 var targetOrigin = &#39;http://b.com&#39;; // 设定接收端的域,*则为不限制   
 ifr.contentWindow.postMessage(&#39;I was there!&#39;, targetOrigin);
};
</script>

数据接收端b.com/index.html中的代码:

<script type="text/javascript">
 window.addEventListener(&#39;message&#39;, function(event){
 // 通过origin属性判断消息来源地址
 if (event.origin == &#39;http://a.com&#39;) {
 alert(event.data); // 弹出"I was there!"
 alert(event.source); // 对a.com、index.html中window对象的引用
   // 但由于同源策略,这里event.source不可以访问window对象
 }
 }, false);
</script>



The above is the detailed content of How to use javascript to achieve cross-domain? Summarize several ways of cross-domain JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn