Created
August 25, 2014 21:53
-
-
Save egermano/8f5357376db9ff44ab62 to your computer and use it in GitHub Desktop.
GTM Youtube Tracker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script src="//www.youtube.com/player_api"></script> | |
<script type="text/javascript"> | |
// attach our YT listener once the API is loaded | |
// | |
var $ = jQuery; | |
// 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 && ; | |
console.log('onPlayerStateChange', e); | |
setTimeout(onPlayerPercent, 1000, e["target"]) | |
if (e["data"] == YT.PlayerState.PLAYING) { | |
dataLayer.push({ | |
event: "youtube", | |
eventCategory: "YouTube Video", | |
eventAction: "play", | |
eventLabel: e.target["getVideoUrl"]().match(/v=([^&]+)/)[1] | |
}); | |
} | |
if (e["data"] == YT.PlayerState.PAUSED) { | |
dataLayer.push({ | |
event: "youtube", | |
eventCategory: "YouTube Video", | |
eventAction: "pause", | |
eventLabel: e.target["getVideoUrl"]().match(/v=([^&]+)/)[1] | |
}); | |
} | |
} | |
// 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", | |
eventCategory: "YouTube Video", | |
eventAction: "error", | |
eventLabel: "GMT 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", | |
eventCategory: "YouTube Video", | |
eventAction: t * 100 + "%", | |
eventLabel: e["getVideoUrl"]().match(/v=([^&]+)/)[1] | |
}) | |
} | |
e["lastP"] != 1 && setTimeout(onPlayerPercent, 1000, e); | |
} | |
} | |
jQuery('iframe').each(function(e){ | |
if (/youtube.com\/embed/.test(jQuery(this).attr('src'))) { | |
var player = new YT.Player(this, { | |
events: { | |
onStateChange: onPlayerStateChange, | |
onError: onPlayerError | |
} | |
}); | |
jQuery(this).data('player', player); | |
} | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment