Alternative analytics tracking for IFrames

Be it for basic form submission, third party content, or even behind-the-scenes logging, IFrames often play important roles in online user behavior. An IFrame (Inline Frame) is an HTML document embedded inside another HTML document on a website, but despite IFrames grant us a lot of flexibility in our sites. They make our analytic tracking code quite harder to implement. Some examples would be cross-domain problems or third party IFrames in which we cannot insert our analytics code. In this post we are going to explain how to treat most of the common issues that IFrames provoques.

IFrames schema


The main idea for this implementation, is that the parent page will always send the hits to analytics. Even the interactions that are coming from the IFrame

In order to achieve that, we will use a JavaScript function of window object called “postMessage”. You can check browser compatibility if you want more information. This function requires two parameters, the first one is the message, and the second one is targetOrigin.

With this function we can send a message from the IFrame to the Main Page. With that being said, we can send our tracking data to the Main page and push it to the dataLayer. Lastly tag manager will do the rest.

Now, let’s see the code and some examples.

To make sure everything will work, we need to standardize the format of the message. In that way the Main page will understand the messages sent by the IFrame.

In this example, we are going to use an object that have two parameters:

  • Action: action we want to do with the data.
    • dataLayer#push
  • Data


IFrame codes:


Above we can see how the function postMessage is called. First parameter is way evident but what we have to know about the second one is that it has to be filled with the main page domain we want to allow or with a ‘*’ character if you do not want to add extra security to the accessibility of your iFrame.

Now we can simply use this function to send any type of data to the Main page and proceed with the Main Page.


In the Main Page, we will have to create a listener whenever we receive a message, then we will process our message and make decisions.

On validDomains we have to add the recognized domains, that we accept messages from. This is used for security terms. Then we can modify the core code of reciveMessage function, to process the data the way we need.



Here we can see the IFrame, which does not have any kind of tag manager or analytics code.

IFrame page

Finally, here we can see some interactions working: to see it live working go here

Main page with IFrame hits

Leave Comment

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

Este sitio usa Akismet para reducir el spam. Aprende cómo se procesan los datos de tus comentarios.