有三個頁面:
a.com/app.html:應用頁面。
a.com/proxy.html:代理文件,通常是一個沒有任何內容的html文件,須要和應用頁面在同一域下。
b.com/data.html:應用頁面須要獲取數據的頁面,可稱爲數據頁面。javascript
實現起來基本步驟以下:html
一、在應用頁面(a.com/app.html)中建立一個iframe,把其src指向數據頁面(b.com/data.html)。數據頁面會把數據附加到這個iframe的window.name上,data.html代碼以下:java
<script type="text/javascript"> window.name = 'I was there!'; // 這裏是要傳輸的數據 </script>
二、在應用頁面(a.com/app.html)中監聽iframe的onload事件,在此事件中設置這個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; // 讀取數據 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>