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 }
三、用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>
能夠看到C頁面正常輸出了B頁面寫入的window.name。