I have an iframe (same domain), and want to be able to track the button usages inside the iframe from the parent page.
The reason I don’t want to embed the tracking directly into the iframe is that I share the iFrame across different pages and want to be able to track it’s unique usage by the parents page tracking events in jQuery.
Sample HTML inside the iFrame:
<a class="btn1" href="1.html">button 1</a>
<a class="btn2" href="2.html">button 2</a>
<a class="btn3" href="3.html">button 3</a>
<a class="btn4" href="4.html">button 4</a>
jQuery inside parent page :
$(document).ready(function() {
$('.btn1').click(function () {
_gaq.push(['_trackEvent', 'iframe page', 'iframe buttons', button 1]);
});
$('.btn2').click(function () {
_gaq.push(['_trackEvent', 'iframe page', 'iframe buttons', button 2]);
});
$('.btn3').click(function () {
_gaq.push(['_trackEvent', 'iframe page', 'iframe buttons', button 3]);
});
$('.btn4').click(function () {
_gaq.push(['_trackEvent', 'iframe page', 'iframe buttons', button 4]);
});
});
This isn’t working though. If I view the parent page source, there’s only the iFrame reference, none of the HTML – so I’m assuming that the parent page doesn’t see any of the iFrames div classes to attached the click event?
I’m very new to jQuery… so apologies if I’m missing some gapingly obvious error!
EDIT 1:
I’ve now tried amending the script on the parent page to:
$(document).ready(function() {
$('.iframe').contents().find('.btn1').click(function () {
alert("Button 1 Pressed!");
});
$('.iframe').contents().find('.btn2').click(function () {
alert("Button 2 Pressed!");
});
$('.iframe').contents().find('.btn3').click(function () {
alert("Button 3 Pressed!");
});
$('.iframe').contents().find('.btn4').click(function () {
alert("Button 4 Pressed!");
});
});
and assigned the iframe the class=”iframe”.
When I click on the button inside the iframe from the parent page – no alert is triggered.
For anyone that stumbles across this thread and is looking for a similar answer – with the help of other stackoverflow posts (and some corrected code from: deantoni) and some long-winded Google threads, this was the solution that I came to that works.
The assumptions are:
The iFrame HTML used:
The iFrame jQuery used:
The Parent Frame jQuery used: