Youtube iframe and Analytics tracking

If you need to use iframe to display youtube video on your website, tracking starts and pauses via analytics can be easily done.
The main trick is to add enablejsapi=1 into url.

E.g.
<iframe width=”560″ id=”somevideo” height=”315″ src=”https://www.youtube.com/embed/aCpGA7OrwyI?autoplay=1&enablejsapi=1″></iframe></pre>

becomes

<iframe width=”560″ id=”somevideo” height=”315″ src=”https://www.youtube.com/embed/aCpGA7OrwyI?autoplay=1&enablejsapi=1“></iframe></pre>

Now you can easily use the API. Feel free to use following example


<iframe width="560" id="somevideo" height="315" src="https://www.youtube.com/embed/aCpGA7OrwyI?autoplay=1&enablejsapi=1"></iframe></pre>

<script>
var player;
function onYouTubeIframeAPIReady() {
    player = new YT.Player( 'somevideo', {
        events: { 'onStateChange': function(state){
            if(state.data){
                if(state.data == YT.PlayerState.PAUSED){
                    // paused
                    ga('send', 'event', 'somevideo', 'paused', creativecoffeebreak.getCurrentTime());
                } else if(state.data == YT.PlayerState.PLAYING){
                    if(!playedAlready){
                        playedAlready = true;
                        ga('send', 'event', 'somevideo', 'start', creativecoffeebreak.getCurrentTime());
                    }
                } else if(state.data == YT.PlayerState.ENDED){
                    ga('send', 'event', 'somevideo', 'finished', creativecoffeebreak.getCurrentTime());
                }
            }
        } }
    });
}

</script>
<script src="https://www.youtube.com/iframe_api"></script>

Please note that the YT.PlayerState.ENDED doesn’t work in almost any browser.
Also, the “PAUSED” event is triggered when fast forwarding as well.

You need to load iframe_api javascript, otherwise the YT object won’t exist.

Write a Comment

Comment