DIV CSS 佈局教程網

跨瀏覽器操作 iframe:子頁面調用父頁面函數的兩種方案
編輯:JavaScript綜合知識     

項目中遇到一個需求:在 iframe 內部操作某個窗體時,需要回調父頁面的一個函數。聽起來簡單,實際寫起來卻在 Chrome 裡反覆報錯。本文記錄整個排查過程與最終方案。

問題現場

父頁面 parent.html:

<html xmlns="https://www.w3.org/1999/xhtml">
<head><title></title>
<script src="jquery-1.10.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
function ParentFunction() {
  alert('ParentFunction');
}
</script></head>
<body>
<input type="button" id="btnCancel" class="button" value="測試" />
<iframe id="FRMdetail" name="FRMdetail" frameborder="0"
        src="child.html" style="width:100%;height:100%;"></iframe>
</body>
</html>

子頁面 child.html:

<html xmlns="https://www.w3.org/1999/xhtml">
<head><title></title>
<script src="jquery-1.10.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
  $("#btnTest").click(function (e) {
    var t = window.parent;
    t.ParentFunction();
  });
});
</script></head>
<body>
<input type="button" id="btnTest" class="button" value="應該獲取的值" />rrr
</body>
</html>

網上流行的 var t = window.parent; t.ParentFunction(); 在 IE 中確實可用,但在 Chrome 裡始終拋出:

Blocked a frame with origin "null" from accessing a frame with origin "null". Protocols, domains, and ports must match.

查了很久都沒找到靠譜答案,網上的方案要麼年代久遠基本失效,要麼互相轉抄、顯然沒人真實測試驗證。最後自己摸索出結論:Chrome 其實支持這種寫法,只是必須通過 HTTP 服務發布後才能正常訪問;如果直接以文件系統協議(file://)打開,就會命中上面那條同源錯誤。這是協議、域名、端口三者必須一致的同源策略在起作用,與代碼本身無關。

更通用的方案:HTML5 postMessage

既然存在同源限制,不如換用 HTML5 提供的 postMessage,它天生就是為跨窗口通信設計的。

父頁面改寫如下:

<html xmlns="https://www.w3.org/1999/xhtml">
<head><title></title>
<script src="jquery-1.10.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
// 掛在 window 上,與直接聲明 function 效果一致
this.ParentFunction = function () {
  alert('ParentFunction');
};
// function ParentFunction() {
//   alert('ParentFunction');
// }

function receiveMessage(e) {
  var data = e.data;
  if (data == "ParentFunction") {
    ParentFunction();
  }
}

// 使用 HTML5 postMessage 必須先綁定 message 事件
if (typeof window.addEventListener != 'undefined') {
  window.addEventListener('message', receiveMessage, false);
} else if (typeof window.attachEvent != 'undefined') {
  window.attachEvent('onmessage', receiveMessage);
}
</script></head>
<body>
<input type="button" id="btnCancel" class="button" value="測試" />
<iframe id="FRMdetail" name="FRMdetail" frameborder="0"
        src="child.html" style="width:100%;height:100%;"></iframe>
</body>
</html>

子頁面則做能力檢測,兩條路徑都留著:

<html xmlns="https://www.w3.org/1999/xhtml">
<head><title></title>
<script src="jquery-1.10.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
  $("#btnTest").click(function (e) {
    var t = window.parent;
    if (!t.ParentFunction) {
      // 直接調用不可行時,改用 HTML5 postMessage
      t.postMessage("ParentFunction", '*');
    } else {
      t.ParentFunction();
    }
  });
});
</script></head>
<body>
<input type="button" id="btnTest" class="button" value="應該獲取的值" />rrr
</body>
</html>

結果與建議

改寫之後,即便在文件系統協議下控制台仍會出現同源提示,但目標方法確實被調用了,功能不受影響。

幾點實踐建議:生產環境應避免把 postMessage 的 targetOrigin 寫成 '*',而是指定明確的源;父頁面在 receiveMessage 中應校驗 e.origin,並對 e.data 做白名單判斷,避免任意頁面都能觸發你的業務函數。此外,若非調試需要,盡量不要把新舊站點放在 file:// 協議下驗證跨窗口通信。

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