Detect Click into Iframe using JavaScript

Russ Bradberry picture Russ Bradberry · Mar 4, 2010 · Viewed 183.4k times · Source

I understand that it is not possible to tell what the user is doing inside an iframe if it is cross domain. What I would like to do is track if the user clicked at all in the iframe. I imagine a scenario where there is an invisible div on top of the iframe and the the div will just then pass the click event to the iframe.

Is something like this possible? If it is, then how would I go about it? The iframes are ads, so I have no control over the tags that are used.

Answer

Paul Draper picture Paul Draper · Apr 23, 2014

This is certainly possible. This works in Chrome, Firefox, and IE 11 (and probably others).

focus();
var listener = window.addEventListener('blur', function() {
    if (document.activeElement === document.getElementById('iframe')) {
        // clicked
    }
    window.removeEventListener('blur', listener);
});

JSFiddle


Caveat: This only detects the first click. As I understand, that is all you want.