Home >Web Front-end >JS Tutorial >How Can I Detect Clicks Inside a Cross-Domain Iframe?

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-01 17:24:11372browse

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

Detecting Clicks within an Iframe

Traditionally, cross-domain iframes pose limitations in detecting user interactions. However, it is possible to track initial clicks within iframes by utilizing an invisible div positioned over the iframe.

Implementation

In modern web browsers, the following JavaScript can be employed to monitor the focus of the browser window:

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 Markup

To complete the setup, the following HTML markup adds the invisible div and the iframe:

<div>

Compatibility

This solution has been verified to function in Chrome, Firefox, and IE 11. It is likely compatible with additional browsers as well.

The above is the detailed content of How Can I Detect Clicks Inside a Cross-Domain Iframe?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn