Skip to content

Instantly share code, notes, and snippets.

@awbauer
Last active October 3, 2018 18:11
Show Gist options
  • Save awbauer/8427056 to your computer and use it in GitHub Desktop.
Save awbauer/8427056 to your computer and use it in GitHub Desktop.
Track downloads with Google Analytics & BU GA tracker
(function ($) {
var filter_from_url = window.location.protocol + "//" + window.location.host,
tracked_types_formatted = '',
trackedTypes = ['pdf'];
trackedTypes.forEach(function(t){
tracked_types_formatted = tracked_types_formatted + "a[href$='."+t+"'],";
});
tracked_types_formatted = tracked_types_formatted.slice(0,-1);
function trackDownload(link, filetype, filename, target) {
var args,
currentPath = location.pathname.split('/');
try {
args = {
category: "file downloaded - /" + currentPath[1],
action: filetype,
label: filename
};
bu_ga_track_event(args);
if( "_blank" == target ){
window.open( link );
} else {
setTimeout(function(){
window.top.location.href = link;
}, 150);
}
} catch (err) {}
return;
}
function bu_ga_track_event(args) {
if (typeof args.value === 'undefined' || typeof args.value === 'null' || isNaN(args.value)) {
args.value = 0;
}
if (typeof args.delay === 'undefined' || typeof args.delay === 'null') {
args.delay = 0;
}
if (typeof args.noninteract === 'undefined' || typeof args.noninteract === 'null') {
args.noninteract = true;
}
args.value = parseFloat(args.value);
var i, trNames = bu_ga_get_trackers();
_gaq.push(['_trackEvent', args.category, args.action, args.label, args.value, args.noninteract]);
for (i = 0; i < trNames.length; i++) {
_gaq.push([trNames[i] + '._trackEvent', args.category, args.action, args.label, args.value, args.noninteract]);
}
if (args.delay) {
setTimeout(function() {
return true;
}, 100);
}
}
$(document).on("click", tracked_types_formatted, function (e) {
var filetype = this.href.split('.').pop(),
path = this.href.replace(window.location.protocol + "//" + window.location.host,"");
e.preventDefault();
trackDownload(this.href, filetype, path, this.target);
});
}(jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment