跨域

同源策略:端口 域名 协议

1 Jsonp

复制代码
 <script>
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'www.baidu.comn&callback=showMessage';
    document.head.appendChild(script);
    function showMessage(res) {
        ...
    }
 </script>
复制代码

动态的创建script,设置一个带参数的网址,通过callback接受返回数据

2 document.domain + iframe跨域

此时有一个限制:主域相同:
例如: http://www.baidu.com 和 http://a.baiud.com,
那么设置:
doncument.domain = 'baidu.comn'

复制代码
 1 1.)父窗口:(http://a.domain.com/a.html)
 2     首先获取 子窗口的数据iframe,然后设置document.domain,
 3 
 4 <iframe id="iframe" src="http://b.domain.com/b.html"></iframe>
 5 <script>
 6     document.domain = 'domain.com';
 7     var iframe  = document.getElementById("iframe")
 8     var win = iframe.contentWindow(获取到了子窗口:window)
 9 </script>
10 2.)子窗口:(http://b.domain.com/b.html)
11 
12 <script>
13     document.domain = 'domain.com';
14     // 获取父窗口中变量
15   </script>
复制代码

3 windows.name + iframe

window都有一个name属性,这个属性:在一个窗口(window)的生命周期内,窗口载入的所有的页面都是共享一个window.name的,而且每个页面对window.name都有读写的权限。

A页面:设置 windows.name = "Monday" 
B页面:console.log(windows.name) // Monday
  1. 加入A页面需要获取B页面的数据,通过中间iframe实现数据的共享,
  2. A页面使用iframe想要获取到B.html,通过window.name设置的数据,需要将iframe的src设置为www.cnblogs.com/B.html即可.
  3. 然后A.html想要得到iframe所获取到的数据,还必须把这个iframe的src设置成跟A.html页面同一个域才行.
  4. 不然根据同源策略,A.html是不能访问到iframe中的window.name属性的。 B.html
    复制代码
     1 <script> 
     2 window.name = "message come from B.html"
     3 </script>
     4 A.html
     5 <iframe id="proxy" src="http://www.cnblogs.com/B.html" onload = "getData()"> 
     6 <script>
     7 function getData(){
     8 var iframe = document.getElementById('proxy);
     9 iframe.onload = function(){
    10 var data = iframe.contentWindow.name;
    11 }
    12 iframe.src = 'b.html';
    13 }
    14 </script>
    复制代码

4 psotMessage

这个功能是h5中新增加的,接受两个参数,第一个:传递的数据,第二个: 协议+主机+端口号

复制代码
 1 A.html
 2 <iframe id="iframe" src="http://b.html"></iframe>
 3 <script>       
 4     var iframe = document.getElementById('iframe');
 5     iframe.onload = function() {
 6         var data = {
 7             name: 'Monday'
 8         };
 9         // 向B页面传送跨域数据
10         iframe.contentWindow.postMessage(JSON.stringify(data), 'http://B.html');
11     };
12 </script>
13 B.html ,如果B发送会A
14 <script>
15     // 接收A的数据,
16     window.addEventListener('message', function(e) {
17         alert('data from domain1 ---> ' + e.data);
18 </script>
复制代码

5 CORS

普通跨域请求:浏览器端写正常的AJAX代码即可,只服务端设置Access-Control-Allow-Origin即可,前端无须设置。

 
原文地址:https://www.cnblogs.com/asasas/p/9471404.html