Home >Web Front-end >JS Tutorial >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!