Alternative analytics tracking for IFrames

Índice de contenidos

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:

 

<script type="text/javascript">
    function sendData(action,data){
        window.top.postMessage({'action':action,'data':data},'targetOrigin');
    }
</script>

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.

<button type="button" name="Accion trackeada" onclick="sendData('dataLayer#push',{'event':'iframeEvent', 'eventAction':'Cool interaction 1!'})">
    Cool interaction 1!
</button>
   ...
<button type="button" name="Accion trackeada" onclick="sendData('dataLayer#push',{'event':'iframeEvent', 'eventAction':'Cool interaction 2!'})">
    Cool interaction 2!
</button>

 

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.

<script type="text/javascript">
    function receiveMessage(event) {
        var validDomains = ['http://valid.domain1.com', 'http://valid.domain2.com', 'http://valid.domain3.com']
        if (validDomains.includes(event.origin)){
            var action = event.data.action;
            var data = event.data.data;
            switch (action) {
              case 'dataLayer#push':
                  dataLayer.push(data);
                  break;
              default:
                  console.log('Unrecognized action: ' + action);
            }
        }
    }
  window.addEventListener("message", receiveMessage, false);
</script>

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.

 

Example:

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

Share on facebook
Share on twitter
Share on linkedin
Share on email
2 min
Suscríbete a nuestra newsletter

Los mejores artículos de analítica digital para potenciar tu negocio.

Deja un comentario

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

Entradas relacionadas

SameSite cookies: prevención de ataques CSRF

SameSite Cookie attribute se deberá definir en las cookies HTTP para prevenir ataques Cross Site Request Forgery (CSRF) en aplicaciones web. No tener definido este atributo en la creación de la cookie implica que esta será ignorada o restringida una vez los navegadores actualicen sus versiones para mejorar los estándares de seguridad.

4 minutos

Dificultad

¿Qué es Gtag y cómo implementarlo para App + Web?

Gtag es una etiqueta de seguimiento que nos permite unificar los productos de Google y que está basada en eventos predefinidos. Es ahora con el lanzamiento de las propiedades de App + Web cuando realmente resulta útil para poder estandarizar y aunar la medición de nuestras apps y webs.

5 minutos

Dificultad

Cómo configurar una propiedad App+Web en Google Analytics

Las nuevas propiedades de App+Web de Google analytics nos permiten añadir hasta 50 flujos de datos de uno u otro tipo. En este artículo te explicamos cómo crear este tipo de propiedades y cómo configurarlas para web.

5 minutos

Dificultad

Ir arriba

Esta web utiliza ‘cookies’ de terceros. Al clicar aceptar está aceptando el uso que realizamos de las cookies. Para más información puede consultar nuestra Política de cookies