Skip to content

Instantly share code, notes, and snippets.

@steffentchr
Created February 2, 2016 12:45
Show Gist options
  • Save steffentchr/10ba03e3c0611a280a3f to your computer and use it in GitHub Desktop.
Save steffentchr/10ba03e3c0611a280a3f to your computer and use it in GitHub Desktop.
Google Analytics tracking module
/*
INTEGRATION: GOOGLE ANALYTICS
*/
Player.provide('integration-google-analytics',
{
googleAnalyticsAccount:'',
googleAnalyticsTrackPlayerPageview:0
},
function(Player,$,opts){
var $this = this;
$.extend($this, opts);
delete $this.container;
var cu = [];
var loaded = false;
var catchup = function(){
$.each(cu, function(i,o){
ga('send', o);
});
cu = [];
}
Player.bind('player:settings', function(e){
PlayerUtilities.mergeSettings($this, ['googleAnalyticsAccount','googleAnalyticsTrackPlayerPageview']);
if($this.googleAnalyticsAccount) {
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', $this.googleAnalyticsAccount, 'auto');
loaded = true;
catchup();
}
});
var currentVideo = {id:'',title:'', type:'clip', duration:0, events:[]};
var trackEvent = function(type,action){
if(typeof(currentVideo.events[type+action])!='undefined') return;
currentVideo.events[type+action] = true;
var title = (currentVideo.type == 'stream' ? 'Live: ' : '') + currentVideo.title;
var url = '/embed/'+currentVideo.id
var o = {
hitType: type,
eventCategory: 'Videos',
eventAction: action,
eventLabel: title,
title: title,
page: url,
location: url
};
if(loaded) {
ga('send', o);
} else {
cu.push(o);
}
}
Player.bind('player:video:loaded', function(e,v){
// Reset the video times
currentVideo = currentVideo = {id:v.photo_id, title:v.title, type:v.type, duration:new Number(v.video_length)||0, events:{}}
// Possibly track a page view
if($this.googleAnalyticsTrackPlayerPageview) trackEvent('pageview', 'Page view');
});
Player.bind('player:video:play', function(e,v){
trackEvent('event', 'Play');
});
Player.bind('player:video:ended', function(e,v){
trackEvent('event', 'Finished');
});
Player.bind('player:actions:overlay:click player:actions:video:click', function(e,v){
trackEvent('event', 'Action clicked');
});
window.setInterval(function(){
if(currentVideo.duration>0) {
var ct = Player.get('currentTime');
if(ct>currentVideo.duration*.25) trackEvent('event', '25 Watched');
if(ct>currentVideo.duration*.50) trackEvent('event', '50 Watched');
if(ct>currentVideo.duration*.75) trackEvent('event', '75 Watched');
if(ct>currentVideo.duration*.99) trackEvent('event', '100 Watched');
}
}, 3000);
}
, false);
Player.use('integration-google-analytics');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment