postMessage 主頁、iframe頁可互相傳值

筆記文:Let's Write

範例1:iframe頁傳訊息給母頁

子頁(iframe.tw)要傳自己的高度給母頁(mother.tw)

iframe.com.tw 傳訊息
/* iframe 的 parent 就是包它的頁面 */
window.addEventListener('load', () => {
  const height = document.body.offsetHeight;
  parent.postMessage(height, 'https://mother.tw'); // https://mother.tw 就是母頁的網域
});
mother.com.tw 接訊息
<iframe id="iframe" src="iframe/index.html"></iframe>
 
<script>
  // 接到 message 要做什麼事的 function
  function receiveMessage(e) {
    // 來源網址(e.origin)不是指定的網域時
    if(e.origin !== 'https://iframe.tw') {
      alert('資料來源錯誤');
      return false;
    }
    // 來源網址是指定的網域時
    else {
      // 拿傳來的參數(e.data)
      const height = e.data;
      document.getElementById('iframe').setAttribute('height', height); // 改變iframe tag height
    }
  }
 
  // 監聽 message 事件
  window.addEventListener('message', receiveMessage, false);
</script>
呈現結果:iframe的高度就是iframe頁面本身的高度,無縫iframe
Demo頁面來源:https://cruip.com/

範例2:母頁傳訊息給iframe頁

母頁(mother.tw)傳訊息給子頁(iframe.tw),讓子頁內容變色。

mother.com.tw 按鈕click時傳訊息
// 抓到iframe的視窗
const iframe = document.getElementById('iframe2').contentWindow;
 
// 按鈕click時傳訊息
document.getElementById('blue').addEventListener('click', () => {
  iframe.postMessage('lightskyblue', 'https://iframe.tw');
});
iframe.com.tw 接到訊息時改變顏色
// 接到 message 要做什麼事的 function
function receiveMessage(e) {
  // 來源網址(e.origin)不是指定的網域時
  if(e.origin !== 'https://mother.tw') {
    alert('資料來源錯誤');
    return false;
  }
  // 來源網址是指定的網域時
  else {
    // 拿傳來的參數(e.data)
    const bgColor = e.data;
    document.querySelector('.box').setAttribute('style', 'background: ' + bgColor);
  }
}
 
// 監聽 message 事件
window.addEventListener('message', receiveMessage, false);
呈現結果:點以下按鈕,iframe中的box會變色

為了認知是iframe,把iframe border給留著。