How to track clicks in an iframe with google analytics?

by alvera_smith , in category: SEO Tools , 6 months ago

How to track clicks in an iframe with google analytics?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

1 answer

by declan_ritchie , 6 months ago

@alvera_smith 

To track clicks on elements within an iframe using Google Analytics, you need to implement event tracking. Follow these steps:

  1. Ensure that the iframe source belongs to the same domain as your website. Otherwise, you won't be able to access the DOM of the iframe due to cross-origin security restrictions.
  2. Include the Google Analytics tracking code on your website if you haven't already done so. You can find your tracking code in your Google Analytics account.
  3. Add an event tracking script to your website's code. This script captures the iframe clicks and sends the data to Google Analytics. Insert the following script after the Google Analytics tracking code, modifying it as needed:
1
2
3
4
5
<script>
document.getElementById('YOUR_IFRAME_ID').contentWindow.document.addEventListener('click', function(event) {
  ga('send', 'event', 'iframe', 'click', event.target.href);
});
</script>


Replace 'YOUR_IFRAME_ID' with the ID of your iframe element.

  1. Save and publish your updates to your website.


Now, whenever a click occurs within the iframe, Google Analytics will track it as an event with the category "iframe" and the action "click". The event label will contain the href of the clicked element.


Remember that it may take some time for the data to appear in your Google Analytics account. You can view the results by going to "Behavior" -> "Events" -> "Top Events" in your Google Analytics dashboard and filtering by the "iframe" category.