這篇文章是對 JavaScript跨域總結與解決辦法 的補充。javascript
有三個頁面:html
a.com/app.html:應用頁面。java
a.com/proxy.html:代理文件,通常是一個沒有任何內容的html文件,須要和應用頁面在同一域下。json
b.com/data.html:應用頁面須要獲取數據的頁面,可稱爲數據頁面。跨域
實現起來基本步驟以下:瀏覽器
在應用頁面(a.com/app.html)中建立一個iframe,把其src指向數據頁面(b.com/data.html)。
數據頁面會把數據附加到這個iframe的window.name上,data.html代碼以下:安全
<script type="text/javascript"> window.name = 'I was there!'; // 這裏是要傳輸的數據,大小通常爲2M,IE和firefox下能夠大至32M左右 // 數據格式能夠自定義,如json、字符串 </script>
在應用頁面(a.com/app.html)中監聽iframe的onload事件,在此事件中設置這個iframe的src指向本地域的代理文件(代理文件和應用頁面在同一域下,因此能夠相互通訊)。app.html部分代碼以下:cookie
<script type="text/javascript"> var state = 0, iframe = document.createElement('iframe'), loadfn = function() { if (state === 1) { var data = iframe.contentWindow.name; // 讀取數據 alert(data); //彈出'I was there!' } else if (state === 0) { state = 1; iframe.contentWindow.location = "http://a.com/proxy.html"; // 設置的代理文件 } }; iframe.src = 'http://b.com/data.html'; if (iframe.attachEvent) { iframe.attachEvent('onload', loadfn); } else { iframe.onload = loadfn; } document.body.appendChild(iframe); </script>
獲取數據之後銷燬這個iframe,釋放內存;這也保證了安全(不被其餘域frame js訪問)。app
<script type="text/javascript"> iframe.contentWindow.document.write(''); iframe.contentWindow.close(); document.body.removeChild(iframe); </script>
總結起來即:iframe的src屬性由外域轉向本地域,跨域數據即由iframe的window.name從外域傳遞到本地域。這個就巧妙地繞過了瀏覽器的跨域訪問限制,但同時它又是安全操做。firefox
參考文章:window.name Transport、Session variables without cookies、使用 window.name 解決跨域問題、利用window.name實現跨域訪問的基本步驟、克軍寫的樣例。