Detecting a Click in an iFrame
Sometimes you need to embed a service in your web pages using an <iframe>
, things like ticket
sales, events calendars etc. There's many great services you, or your clients might want to offer to their users
that work this way
However, if this is a cross domain iframe (embedding a page or resource that loads on a domain not under your control), unless you have the ability to add tracking codes to these pages, you might not know if your visitors are interacting with these services at all.
One solution might be to overlay a heatmap, and track the usage that way, but that can be problematic if the iframe requires scrolling, or resizes between your mobile & desktop users. The benefit is you might have some idea of what they are clicking on in this external site. But if this isn't practical, and you just want to know if someone has clicked in the frame, the following code will do the job.
Example:
The Code:
<script>
var iframewatcher = setInterval(function(){
var activeE = document.activeElement;
if(activeE && activeE.tagName == 'IFRAME'){
// Just setting text as example, in this case in a div with the id="alertdiv", but this could be an ajax call, fire an analytics event, whatever action you need.
alertdiv.textContent = 'A click happened in the iframe, Party time, excellent!';
clearInterval(iframewatcher);
}
}, 100);
</script>
In this example, we use the click detection to simply add some text to a div, but you could just as easily make an ajax call to record the data, or even trigger a google analytics event.