DIV CSS 佈局教程網

父頁面如何呼叫 iframe 子頁面的函式(雙向範例)
編輯:關於JavaScript     

frame 架構下,父子頁面互相呼叫函式是很基本的需求。這裡要注意一個關鍵:跨瀏覽器時,iframe 的 name 屬性比 id 可靠。

父頁面:parent.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>parent</title>
<script>
  function parentFunction() {
    alert('function in parent');
  }

  function callChild() {
    child.window.childFunction();
    /*
      child 是 iframe 的 name 屬性值,
      不能寫成 id —— 在 Firefox 下 id 取不到 iframe 物件
    */
  }
</script>
</head>
<body>
<input type="button" name="call child" value="call child" onclick="callChild()"/>
<br/><br/>
<iframe name="child" src="./child.html" ></iframe>
</body>
</html>

子頁面:child.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>child</title>
<script>
  function childFunction() {
    alert('function in child');
  }

  function callParent() {
    parent.parentFunction();
  }
</script>
</head>
<body>
<input type="button" name="call parent" value="call parent" onclick="callParent()"/>
</body>
</html>

呼叫路徑怎麼看

父呼叫子:直接用 iframe 的 name 當作 window 屬性,再取它的 window 物件。child.window.childFunction() 就是「找到 name 為 child 的視窗,呼叫裡面的函式」。

子呼叫父:用 parent 指向上一層視窗。若巢狀多層,parent.parent 往上兩層,或直接用 top 指向最外層。

關鍵前提:必須同源。 父頁面與 iframe 內容必須來自相同的通訊協定、網域與連接埠,否則瀏覽器的同源政策會直接阻擋跨文件的存取,並在 console 丟出安全性錯誤。

更穩妥的寫法

直接依賴 name 當全域變數有風險——若頁面上剛好有個同名的元素或變數,就會取到錯誤的物件。比較明確的做法是透過 document.getElementById 或 document.getElementsByName 取得 iframe,再存它的 contentWindow:

var frame = document.getElementById('childFrame');
frame.contentWindow.childFunction();

另外,呼叫前最好先確認對方的函式真的存在,特別是 iframe 可能尚未載入完成:

if (frame.contentWindow && typeof frame.contentWindow.childFunction === 'function') {
  frame.contentWindow.childFunction();
}

跨來源時的正確工具:postMessage

如果父子頁面不同源,上面所有方法都會失敗,此時必須用 postMessage:

// 父頁面:監聽子頁面訊息
window.addEventListener('message', function(event){
  // 務必檢查來源,別信任任何傳來的訊息
  if (event.origin !== 'https://child.example.com') return;
  handleChildMessage(event.data);
});

// 父頁面:傳訊息給子頁面
document.getElementById('childFrame').contentWindow
  .postMessage({ type: 'setHeight', value: 800 }, 'https://child.example.com');
// 子頁面:接收並回覆
window.addEventListener('message', function(event){
  if (event.origin !== 'https://parent.example.com') return;
  if (event.data.type === 'setHeight') {
    document.body.style.height = event.data.value + 'px';
  }
});

window.parent.postMessage({ type: 'ready' }, 'https://parent.example.com');

使用 postMessage 有兩個必做的安全措施:一定要指定目標 origin(不要寫 *),以及接收時一定要檢查 event.origin。少了這兩步,任何網站都能對你的頁面發送訊息,形成資訊洩漏或惡意操作的風險。

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