javascript跨域總結(jié)之window.name實現(xiàn)的跨域數(shù)據(jù)傳輸
自己實踐了一下,真的很好用。特將具體實現(xiàn)方法記錄如下
有三個頁面:
a.com/app.html:應用頁面。
a.com/proxy.html:代理文件,一般是一個沒有任何內(nèi)容的html文件,需要和應用頁面在同一域下。
b.com/data.html:應用頁面需要獲取數(shù)據(jù)的頁面,可稱為數(shù)據(jù)頁面。
實現(xiàn)起來基本步驟如下:
在應用頁面(a.com/app.html)中創(chuàng)建一個iframe,把其src指向數(shù)據(jù)頁面(b.com/data.html)。
數(shù)據(jù)頁面會把數(shù)據(jù)附加到這個iframe的window.name上,data.html代碼如下:
<script type="text/javascript"> window.name = 'I was there!'; // 這里是要傳輸?shù)臄?shù)據(jù),大小一般為2M,IE和firefox下可以大至32M左右 // 數(shù)據(jù)格式可以自定義,如json、字符串 </script>
在應用頁面(a.com/app.html)中監(jiān)聽iframe的onload事件,在此事件中設(shè)置這個iframe的src指向本地域的代理文件(代理文件和應用頁面在同一域下,所以可以相互通信)。app.html部分代碼如下:
<script type="text/javascript"> var state = 0, iframe = document.createElement('iframe'), loadfn = function() { if (state === 1) { var data = iframe.contentWindow.name; // 讀取數(shù)據(jù) alert(data); //彈出'I was there!' } else if (state === 0) { state = 1; iframe.contentWindow.location = "http://a.com/proxy.html"; // 設(shè)置的代理文件 } }; iframe.src = 'http://b.com/data.html'; if (iframe.attachEvent) { iframe.attachEvent('onload', loadfn); } else { iframe.onload = loadfn; } document.body.appendChild(iframe); </script>
獲取數(shù)據(jù)以后銷毀這個iframe,釋放內(nèi)存;這也保證了安全(不被其他域frame js訪問)。
<script type="text/javascript"> iframe.contentWindow.document.write(''); iframe.contentWindow.close(); document.body.removeChild(iframe); </script>
總結(jié)起來即:iframe的src屬性由外域轉(zhuǎn)向本地域,跨域數(shù)據(jù)即由iframe的window.name從外域傳遞到本地域。這個就巧妙地繞過了瀏覽器的跨域訪問限制,但同時它又是安全操作。
相關(guān)文章
JS pushlet XMLAdapter適配器用法案例解析
這篇文章主要介紹了JS pushlet XMLAdapter適配器用法案例解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-10-10淺析javascript中函數(shù)聲明和函數(shù)表達式的區(qū)別
這篇文章主要介紹了淺析javascript中函數(shù)聲明和函數(shù)表達式的區(qū)別,需要的朋友可以參考下2015-02-02BootStrap中Table隱藏后顯示問題的實現(xiàn)代碼
這篇文章主要介紹了BootStrap中Table隱藏后顯示問題的實現(xiàn)代碼,需要的朋友可以參考下2017-08-08js下通過getList函數(shù)實現(xiàn)分頁效果的代碼
js下通過getList函數(shù)實現(xiàn)分頁效果的代碼,需要通過js分頁的朋友可以參考下。2010-09-09