Sometimes, we want to check if a user clicked into an iframe using JavaScript.
In this article, we’ll look at how to detect clicks into an iframe with JavaScript.
Focus on the Main Window Then Add a blur Event Listener to the Window
We can focus on the main window and then add a blur
event listener to the window to see which element is activated after the blur
event is emitted by the window.
For instance, if we have the following iframe:
<iframe src='https://example.com'>
</iframe>
Then we can focus on on the window and add a blur
listener to it by writing:
focus();
const listener = window.addEventListener('blur', () => {
if (document.activeElement === document.querySelector('iframe')) {
console.log('clicked on iframe')
}
window.removeEventListener('blur', listener);
});
We call focus
to focus on the main window.
Then we call window.addEventListener
to add a blur
event listener to the window.
In the event listener, we check if document.activeElement
is the iframe to check if the iframe is the element that we focused on.
If it is, then we log a message.
Then we immediately remove the blur
event listener after that.
Now when we click on the iframe, we should see the ‘clicked on iframe’ message logged.
Conclusion
We can detect clicks in an iframe with JavaScript by listening to the blur
event on the window.