11/2/14

Como medir videos de Youtube con GTM

Hola de nuevo,

Hace algún tiempo que no escribo, he estado muy liado con un nuevo proyecto que tengo entre manos, a ver si en cuanto se estabilice puedo retomar el blog.

Hoy vamos a ver una forma de medir los videos de Youtube embebidos en una web utilizando Google Tag Manager. Este artículo lo he sacado de un post de Stéphane Hamel en el blog de CardinalPath, por si queréis leer el original (en inglés), que me lo pasó mi buen amigo Carlos M. Lebrón (@analisisweb).


Voy a incluir un video de prueba, para poder ver como recoge Google Analytics los datos.

Bueno, he escogido un video cualquiera, en este caso uno del canal de Google Analytics, quiero que lo veáis, pero quiero que algunos lo hagáis hasta el final y otros cortéis cuando os apetezca, para ver como analytics mide los ususarios que visionan el 25, 50, 75 y 100% del video, cuantos le dan al play y cuantos al pausa. 

Primero vamos a ver como configurar todo esto con GTM para más tarde poder ver los datos.

Lo primero que necesitamos, es hacer uso de la API de JavaScript de Youtube, para poder controlar las interacciones de los usuarios con los controles del video. Para ellos simplemente tenemos que incluir "enablejsapi=1" en el enlace del video, por ejemplo:

<iframe width="560" height="315" src="//www.youtube.com/embed/5Dw2I5Uxmk8?list=PL96382D7913797880?enablejsapi=1" frameborder="0" allowfullscreen></iframe> 

Una vez que ya hemos incluido "enablejsapi=1" al código del enlace del video vamos a construir las macros, las etiquetas y las reglas necesarias en GTM.

MACROS

¿Hay video Youtube?
Creamos una nueva macro con los siguientes parámetros:

Macro Name: Youtube is present
Macro Type: JavaScript Personalizado
Custom JavaScript:
// Return "true" if there is at least one Youtube video on the page
function () {
    for (var e = document.getElementsByTagName('iframe'), x = e.length; x--;)
        if (/youtube.com\/embed/.test(e[x].src)) return true;
    return false;
}
  
Evento 
Creamos un evento como el siguiente:

Macro Name: event
Macro Type: Custom Event

Datalayer Action 

Macro Name: dataLayer action
Macro Type: Data Layer Variable
Data Layer Variable Name: action

Datalayer Label

Macro Name: dataLayer label
Macro Type: Data Layer Variable
Data Layer Variable Name: label

ETIQUETAS

Youtube Listener

Tag Name: Youtube Listener
Tag Type: Custom HTML Tag
Firing Rule: Youtube present
HTML: <script type="text/javascript">
// attach our YT listener once the API is loaded
function onYouTubeIframeAPIReady() {
    for (var e = document.getElementsByTagName("iframe"), x = e.length; x--;) {
        if (/youtube.com\/embed/.test(e[x].src)) {
            new YT.Player(e[x], {
                events: {
                    onStateChange: onPlayerStateChange,
                    onError: onPlayerError
                }
            });
            YT.gtmLastAction = "p";
        }
    }
}

// listen for play/pause, other states such as rewind and end could also be added
// also report % played every second
function onPlayerStateChange(e) {
    e["data"] == YT.PlayerState.PLAYING && setTimeout(onPlayerPercent, 1000, e["target"]);
    if (e["data"] == YT.PlayerState.PLAYING && YT.gtmLastAction == "p") {
        dataLayer.push({
            event: "youtube",
            action: "play",
            label: e.target["getVideoUrl"]().match(/v=([^&]+)/[1]
        )});
        YT.gtmLastAction = "";
    }
    if (e["data"] == YT.PlayerState.PAUSED) {
        dataLayer.push({
            event: "youtube",
            action: "pause",
            label: e.target["getVideoUrl"]().match(/v=([^&]+)/[1]
        )});
        YT.gtmLastAction = "p";
    }
}

// catch all to report errors through the GTM data layer
// once the error is exposed to GTM, it can be tracked in UA as an event!
function onPlayerError(e) {
    dataLayer.push({
        event: "error",
        action: "GTM",
        label: "youtube:" + e["target"]["src"] + "-" + e["data"]
    })
}

// report the % played if it matches 0%, 25%, 50%, 75% or completed
function onPlayerPercent(e) {
    if (e["getPlayerState"]() == YT.PlayerState.PLAYING) {
        var t = e["getDuration"]() -
        e["getCurrentTime"]() <= 1.5 ? 1 :
        (Math.floor(e["getCurrentTime"]() / e["getDuration"]() *
        4) / 4).toFixed(2);         if (!e["lastP"] || t >
        e["lastP"]) {
            e["lastP"] = t;
            dataLayer.push({
                event: "youtube",
                action: t * 100 + "%",
                label: e["getVideoUrl"]().match(/v=([^&]+)/[1]
            )});
        }
        e["lastP"] != 1 && setTimeout(onPlayerPercent, 1000, e);
    }
}

// load the Youtube JS api and get going
var j = document.createElement("script"),
    f = document.getElementsByTagName("script")[0];
j.src = "//www.youtube.com/iframe_api";
j.async = true;
f.parentNode.insertBefore(j, f);
</script>

Youtube Event

Tag Name: Youtube Event
Tag Type: Google Analytics
Tracking ID: UA-XXXXXX-Y
Track Type: Event
Event Tracking Parameters:
Category: {{event}}
Action: {{dataLayer action}}
Label: {{dataLayer label}}
Firing rule: Youtube event

En esta etiqueta, para todos aquellos que utilicen Universal Analytics, solo tienen que cambiar el tipo de etiqueta por Universal Analytics.

REGLAS

Video Youtube detectado

Rule Name: Youtube present
Conditions: {{event}} equals gtm.dom AND {{youtube is present}} equals true

Algo nos dice Youtube 

Rule Name: Youtube event
Conditions: {{event}} equals youtube

Bien, una vez configurado todo esto, ya solo queda crear la versión y publicar, ¡¡y por supuesto medir!!.

Esto es todo por hoy ¿Te ha gustado este post? ¡Compártelo!

No hay comentarios:

Publicar un comentario