Skip to content

Instantly share code, notes, and snippets.

@ao5357
Created June 20, 2021 19:32
Show Gist options
  • Save ao5357/433e5e2c6a8326daf236334514511951 to your computer and use it in GitHub Desktop.
Save ao5357/433e5e2c6a8326daf236334514511951 to your computer and use it in GitHub Desktop.
Drupal theme javascript with a YouTube GA event tracker
/**
* @file
* JavaScript for this theme.
*/
/**
* Empty function the the YouTube iframe API requires.
*/
var youtubePlayers = [];
function onYouTubeIframeAPIReady() {
// Get closer to the theme context and jQuery.
Drupal.behaviors.thisTheme.youtube();
}
(function ($, Drupal) {
Drupal.behaviors.thisTheme = {
attach: function (context, settings) {
if (context === document) {
/**
* Function for making YouTube events GA events.
*/
var youtubeOnStateChange = function(e) {
if (typeof ga === 'function') {
// Track YouTube events in GA.
// Let's get the event type/action first.
var eventAction = 'unspecified';
switch (e.data) {
case YT.PlayerState.UNSTARTED:
eventAction = 'unstarted';
break;
case YT.PlayerState.ENDED:
eventAction = 'ended';
break;
case YT.PlayerState.PLAYING:
eventAction = 'play';
break;
case YT.PlayerState.PAUSED:
eventAction = 'pause';
break;
case YT.PlayerState.BUFFERING:
eventAction = 'buffering';
break;
case YT.PlayerState.CUED:
eventAction = 'cued';
break;
}
// Other GA event settings.
var eventLabel = (e.target.j.videoData.title.length) ? e.target.j.videoData.title : 'unspecified';
var eventValue = (e.target.j.currentTime >= 0) ? Math.ceil(e.target.j.currentTime) : 0;
// Send off the GA event.
ga('send', 'event', {
'eventCategory': 'YouTube',
'eventAction': eventAction,
'eventLabel': eventLabel.trim().substr(0, 140).trim(),
'eventValue': eventValue,
transport: 'beacon'
});
}
};
// Utility function for YouTube URLs.
var youtubeParser = function (url) {
var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
var match = url.match(regExp);
return (match && match[7].length === 11) ? match[7] : false;
};
// Make YouTube links pop in to replace the button.
var $ytLink = $('main a[href*="youtube.com"]');
if ($ytLink.length) {
$ytLink.addClass('ytlink-init');
// Asynchronously add the YouTube iframe API.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
$ytLink.on('click', function (e) {
e.stopPropagation();
var $this = $(this);
var watchCode = youtubeParser($this.attr('href'));
$this.replaceWith('<iframe id = "' + watchCode + '" ' +
'src="https://www.youtube.com/embed/' + watchCode + '?enablejsapi=1" ' +
'allowfullscreen frameborder="0" height="480" width="854"></iframe>');
// Create a listener for stateChange events on the player.
if (YT && typeof YT === 'object') {
youtubePlayers.push(new YT.Player(watchCode, {
events: {
'onStateChange': youtubeOnStateChange
}
}));
}
return false;
});
}
}
},
youtube: function () {
// Perhaps do nothing.
}
};
})(jQuery, Drupal);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment