How to Detect User Clicks within an Iframe
Challenge:
Determining whether a user has clicked within an iframe can be challenging, especially when the iframe originates from a different domain (known as cross-domain iframes).
Solution:
To detect clicks within an iframe, a clever workaround can be employed using an invisible div positioned directly above the iframe's boundary. When the user clicks anywhere within the iframe, the div intercepts the click event and forwards it to the iframe.
Implementation:
In the main document, create the following elements:
<div>
Then, insert the following JavaScript code:
const message = document.getElementById("message"); window.focus(); window.addEventListener("blur", () => { setTimeout(() => { if (document.activeElement.tagName === "IFRAME") { message.textContent = "clicked " + Date.now(); console.log("clicked"); } }); }, { once: true });
Explanation:
This technique provides a reliable way to track whether a user has clicked within an iframe, even when it is cross-domain.
The above is the detailed content of How Can I Reliably Detect Clicks Inside a Cross-Domain Iframe?. For more information, please follow other related articles on the PHP Chinese website!