How to track iframes with Google tag manager.

“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.

<script>
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, 'https://domain.com/');
}
} catch (e) {
window.console && window.console.log(e);
}
</script>

Where https://domain.com we must put the domain of parent website.

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

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 .