首頁 >web前端 >js教程 >如何偵測跨域 iframe 內的點擊?

如何偵測跨域 iframe 內的點擊?

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-12-01 17:24:11489瀏覽

How Can I Detect Clicks Inside a Cross-Domain Iframe?

偵測 Iframe 內的點擊

傳統上,跨域 iframe 在偵測使用者互動方面有其限制。但是,可以透過利用位於 iframe 上的不可見 div 來追蹤 iframe 內的初始點擊。

實作

在現代Web 瀏覽器中,可以使用以下JavaScript用於監控瀏覽器視窗的焦點:

const message = document.getElementById("message");

// Ensure the main document is focused to trigger window blur when the iframe is interacted with.
window.focus();

window.addEventListener("blur", () => {
  setTimeout(() => {
    if (document.activeElement.tagName === "IFRAME") {
      message.textContent = "clicked " + Date.now();
      console.log("clicked");
    }
  });
}, { once: true });

HTML標記

為了完成設置,以下HTML 標記添加了不可見的div和 iframe:

<div>

相容性

此解決方案已被驗證可在 Chrome、Firefox 和 IE 11 中運作。它可能與其他瀏覽器相容,因為好吧。

以上是如何偵測跨域 iframe 內的點擊?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn