自己實(shí)踐了一下,真的很好用。特將具體實(shí)現(xiàn)方法記錄如下
有三個(gè)頁面:
a.com/app.html:應(yīng)用頁面。
a.com/proxy.html:代理文件,一般是一個(gè)沒有任何內(nèi)容的html文件,需要和應(yīng)用頁面在同一域下。
b.com/data.html:應(yīng)用頁面需要獲取數(shù)據(jù)的頁面,可稱為數(shù)據(jù)頁面。
實(shí)現(xiàn)起來基本步驟如下:
在應(yīng)用頁面(a.com/app.html)中創(chuàng)建一個(gè)iframe,把其src指向數(shù)據(jù)頁面(b.com/data.html)。
數(shù)據(jù)頁面會(huì)把數(shù)據(jù)附加到這個(gè)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>
在應(yīng)用頁面(a.com/app.html)中監(jiān)聽iframe的onload事件,在此事件中設(shè)置這個(gè)iframe的src指向本地域的代理文件(代理文件和應(yīng)用頁面在同一域下,所以可以相互通信)。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ù)以后銷毀這個(gè)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從外域傳遞到本地域。這個(gè)就巧妙地繞過了瀏覽器的跨域訪問限制,但同時(shí)它又是安全操作。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注