How to track iframes with Google tag manager.

Posted on

Iframe is a method to embed other websites inside a website, that is not used any more when we build websites.

But what if we need to implement an iframe on our website and we also need to collect data from this iframe to the google analytics of the main site?

Well, there is a way even if it is a little bit tricky. Let’s see the steps. First of all, we must have access to the backend code of the iframe website.
Then we put the following code to the head of iframe website.

try {
if ('{{GoogleAnalyticsID}}' === 'UA-xxxxxxxxx-x') {
var postObject = JSON.stringify({
event: 'my-custom-event',
data: {
'path': '{{Page Hostname}}{{Page Path}}',
'event': {{Event}}
parent.postMessage(postObject, '');
} catch (e) {
window.console && window.console.log(e);

Where we must put the domain of parent website.

  • Then we add a custom html tag on the website that contains the iframe
(function(_w, _d){
_w.addEventListener('message', function(event) {
var data = JSON.parse(;
var dataLayer = window.dataLayer || (window.dataLayer = []);
event: data.event,
data: data
window.console && window.console.log(e);

On both scripts, we must add the custom events that we will create in our Google console so we can track the events.

So the final steps that we need to take are :

  • Setup a custom trigger to listen for the custom event you are emitting (cb-pageview)
  • Create datalayer variables to allow data from the event to be used.
  • Set up a Google Analytics tag and trigger it with the custom event and use the datalayer variables.
    If everything will be set up correctly in the Google console of the main website we should see two Google tracker codes. One for the Parent and one for the iframe.”

Keep an eye on our blog for new content . If you have difficulty to follow the steps above don’t hesitate to contact us for help .