web跨域通讯问题解决

Web页面的跨域问题产生缘由是企图使用JS脚本读写不一样域的JS做用域。问题根源来自JavaScript的同源策略:出于安全考虑,Javascript限制来自不一样源的web页面JS脚本之间进行交互。不然就会出现各类获取用户私密数据的问题。javascript

一、document.domainhtml

它只能只能解决一个域名下的不一样二级域名页面跨域,例如person.aa.com与book.aa.com,能够将book.aa.com用iframe添加到 person.aa.com的某个页面下,在person.aa.com和iframe里面都加上document.domain = "aa.com"。java

二、Jsonpweb

Jsonp能够解决XmlHttpRequest请求不能跨域的限制,原理是经过动态建立一个<script> 元素来请求一段JS脚本,让这段脚本在页面做用域里执行,迂回实现相似Ajax的请求。跨域

 1 //加载js文件
 2 function load_script(url, callback){  
 3     var head = document.getElementsByTagName('head')[0];  
 4     var script = document.createElement('script');  
 5     script.type = 'text/javascript';  
 6     script.src = url;  
 7     script.onload = script.onreadystatechange = function(){  
 8 if((!this.readyState||this.readyState === "loaded"||this.readyState === "complete")){  
 9             callback && callback();  
10             // Handle memory leak in IE  
11             script.onload = script.onreadystatechange = null;  
12             if ( head && script.parentNode ) {  
13               head.removeChild( script );  
14             }  
15         }  
16     };   
17     head.insertBefore( script, head.firstChild );  
18 }
View Code

三、用HTML5的API浏览器

HTML5提供了一个可让咱们跨域通讯的API:postMessage,支持的浏览器有 Internet Explorer 8.0+, Chrome 2.0+、Firefox 3.0+, Opera 9.6+, 和 Safari 4.0+。window.postMessage方法被调用时,目标窗口的message事件即被触发,这样能够实现不一样域直接的信息交流。安全

假设A页面中包含iframe B页面dom

 1 var winB = window.frames[0];
 2  
 3 winB.postMessage('hello iframe', 'http://www.test.com');
 4  
 5 //B页面(监听message事件、获取信息)
 6  
 7 window.addEventListener('message',function(e){
 8  
 9 // ensure sender's origin
10  
11 if(e.origin == 'http://www.aa.com'){
12  
13     console.log('source: ' + e.source);
14  
15     console.log('Message Received: ' + e.data);
16  
17 }
18  
19 },false) 

PS. 通讯事件没有冒泡.ide

四、window.namepost

window.name通常用来获取子窗口:window.frames[windowName];它有个重要特色:一个窗口不管加载什么页面,window.name都保持不变。而这个特色能够用来进行跨域信息传递。例如3个页面分别为A、B、C。A是主页面,里面嵌入了一个iframe:B页面。B页面对window.name进行赋值,接下来重定向到C页面。C页面在另一个域里面,它的功能就是读取出B页面写入的window.name。

 1 <!-- A页面 -->
 2 <html>
 3 <head>
 4 <title> Page A</title>
 5 </head>
 6 <body>
 7     <iframe src=”B.html” />
 8 </body>
 9 </html>
10 
11 <!-- B页面 -->
12 <html>
13 <head>
14 <title> Page B </title>
15 </head>
16 <body> 
17 <script language=”JavaScript”>
18 var a = [];
19 for (var i = 0;i < 10; i++){
20     a.push(’xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx’+i);
21 }
22 window.name= a.join(''); //写入window.name,这里能够写入一个比较大的值
23 window.location.href = ‘http://www.cc.com/C.html’;
24 </script>
25 </body>
26 </html>
27 
28 <!-- C页面 -->
29 <html>
30 <head>
31 <title> Page C </title>
32 </head>
33 <body>
34 <script language=”JavaScript”>
35 document.write(window.name);//读出window.name,并写到页面上
36 </script>
37 </body>
38 </html>
View Code

能够看到C页面正常输出了B页面写入的window.name。

相关文章
相关标签/搜索