萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 偵測 iframe 內頁面捲動到底部並觸發事件

應用場景

嵌入第三方頁面 (如使用者協議、廣告頁) 時,需確認使用者已閱讀至底部才啟用「同意」按鈕或觸發後續流程。

關鍵屬性說明

  • clientHeight:元素可視區域高度 (含 padding,不含捲動條)
  • scrollHeight:元素內容總高度 (含被捲動隱藏部分)
  • scrollTop:目前捲動距離頂部的像素值
  • 觸底條件:scrollTop + clientHeight >= scrollHeight (或 scrollTop === scrollHeight - clientHeight)

完整實作程式碼

<iframe src="~/Files/3.html" id="iframepage" width="825" onload="initIframe()"></iframe>

<script type="text/javascript">
function initIframe() {
  var ifm = document.getElementById('iframepage');
  // 自動調整 iframe 高度 (視需求)
  ifm.height = window.document.body.clientHeight - 100;
  
  // 綁定捲動事件 (需同域或 CORS 允許)
  try {
    ifm.contentWindow.onscroll = function() {
      var doc = ifm.contentWindow.document.documentElement;
      // 兼容 body 捲動情況
      var scrollTop = doc.scrollTop || ifm.contentWindow.document.body.scrollTop;
      var scrollHeight = doc.scrollHeight;
      var clientHeight = doc.clientHeight;
      
      if (scrollTop + clientHeight >= scrollHeight - 5) { // 5px 容差
        alert('已捲動到底部!');
        // 這裡可啟用按鈕、發送追蹤事件等
      }
    };
  } catch (e) {
    console.error('跨域限制無法存取 iframe 內容:', e);
    // 跨域情況需使用 postMessage 通訊
  }
}
</script>

跨域限制與解決方案

同源策略阻擋存取不同源 iframe 的 contentWindow.document。Chrome 需在伺服器環境 (非 file://) 才能正常運作。

方案一:postMessage (推薦,支援跨域)

// 父頁面
window.addEventListener('message', function(e) {
  if (e.data.type === 'iframeScrollBottom') {
    console.log('iframe 通知已到底部');
  }
});

// iframe 內頁面 (需可控制其代碼)
window.addEventListener('scroll', function() {
  var doc = document.documentElement;
  if (doc.scrollTop + doc.clientHeight >= doc.scrollHeight - 5) {
    parent.postMessage({ type: 'iframeScrollBottom' }, '*'); // 生產環境指定具體 origin
  }
});

方案二:代理頁面 (同域)

將目標頁面透過後端代理至同域下載入,繞過同源限制。

實作時請務必處理跨域例外,並在 iframe 頁面載入完成後再綁定事件。

copyright © 萬盛學電腦網 all rights reserved