DIV CSS 佈局教程網

JavaScript 與 iframe 的溝通術:同域讀寫與跨域 hash 通信
編輯:JavaScript綜合知識     

iframe 裡的頁面和父頁面要互相傳資料,難度完全取決於「同不同源」。同域時輕鬆讀寫;跨子域只要設定 document.domain 也能打通;真正完全不同的網域,就只能靠改寫 location.hash 這種迂迴手段。以下分三種情境說明。

一、同域或跨子域:直接讀寫對方節點

父頁面操作子頁面:

<iframe id="test-iframe" name="test-iframe" src="child.html"
        scrolling="no" frameborder="0"></iframe>
<script>
window.onload = function () {
  // 兩種取法都可以。IE6、IE7 不支援 contentDocument,
  // 所以用 window.frames["name"] 這種通用寫法最保險
  var d = window.frames["test-iframe"].document;
  d.getElementsByTagName('h1')[0].innerHTML = 'pp';
  alert(d.getElementsByTagName('h1')[0].firstChild.data);
}
</script>

注意:一定要在 window.onload 之後才去碰 iframe 內的節點,否則瀏覽器會丟出「拒絕存取」。實測在 IE8、Firefox 3.6、Opera 11 上,DOMReady 階段也能讀取。

子頁面操作父頁面:

<script>
parent.document.getElementsByTagName('h1')[0].innerHTML = 'pp';
alert(parent.document.getElementsByTagName('h1')[0].firstChild.data);
</script>

小結

  • 測試通過:IE6、IE7、IE8、Firefox 2.0/3.0/3.6、Chrome 8、Opera 11、Safari 5。
  • document.getElementById('idName').contentDocument 與 window.frames["iframeName"].document 等價。
  • 跨子域時,父頁面與子頁面的 JS 都要加上 document.domain = 'xxx.com';。

二、完全跨域:用 hash 傳遞訊息

兩個頁面網域不同時,直接存取對方 document 一定失敗。可行的做法是改寫對方網址的 hash 部分,讓對方輪詢偵測。

父頁面:

<iframe id="test-iframe" src="https://www.yyy.com/child.html"
        scrolling="no" frameborder="0"></iframe>
<input type="button" value="send" onclick="sendRequest()" />
<script>
function sendRequest() {
  document.getElementById('test-iframe').src += '#a';
}

var interval = window.setInterval(function () {
  if (location.hash) {
    alert(location.hash);
    window.clearInterval(interval);
  }
}, 1000);
</script>

子頁面:

<h1>RRRRRR</h1>
<script>
var url = 'https://www.xxx.com/father.html';
var oldHash = self.location.hash,
    newHash,
    interval = window.setInterval(function () {
      newHash = self.location.hash;
      if (oldHash != self.location.hash) {
        document.getElementsByTagName('h1')[0].innerHTML = 'pp';
        // alert(parent.location.href); // 打開這行瀏覽器會提示無權限
        parent.location.href = url + '#b';
        window.clearInterval(interval);
      }
    }, 500);
</script>

小結

  • IE6、IE7 以外的瀏覽器,改動 hash 都會被記進 history;IE6、IE7 不會。
  • 曾嘗試用 parent.location.replace 避免父頁面向伺服器發請求,理論上就不會留下歷史紀錄,但實測無效。
  • 子頁面無權讀取父頁面的 url,但可以寫入。所以跨域溝通前,必須事先知道父頁面的網址。

結論很實際:前端解決跨域的能力天生受限,hash 輪詢只是權宜之計。真正的跨域資料交換,還是交給伺服器端方案(代理、CORS、JSONP 或訊息佇列)會乾淨得多。而如果是現代專案,postMessage 才是跨域 iframe 溝通的正規途徑。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved