Created
March 12, 2012 13:25
-
-
Save caillou/2021918 to your computer and use it in GitHub Desktop.
Track mailto, file download and external links using Google Analytics
This file contains hidden or 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
/*globals pageTracker: true */ | |
(function () { | |
"use strict"; | |
var delegate, clickCallback, handleLink, track; | |
// generic delegate function | |
delegate = function (element, tagName, eventName, callback) { | |
var eventListener; | |
tagName = tagName.toLowerCase(); | |
eventListener = function (event) { | |
var target = event.target; | |
while (target !== document.body && target !== element) { | |
if (target.tagName && target.tagName.toLowerCase() === tagName) { | |
callback.call(target, event); | |
break; | |
} | |
target = target.parentNode; | |
} | |
}; | |
if ("function" === typeof element.addEventListener) { | |
element.addEventListener(eventName, eventListener); | |
} else if ("function" === typeof element.attachEvent) { | |
element.attachEvent("on" + eventName, eventListener); | |
} | |
}; | |
track = function (page) { | |
if ("object" === typeof(pageTracker) && "function" === typeof pageTracker._trackPageview) { | |
pageTracker._trackPageview(page); | |
} | |
}; | |
handleLink = function (element) { | |
var page; | |
page = (element.pathname.charAt(0) === "/") ? element.pathname : "/" + element.pathname; | |
if (element.search && element.pathname.indexOf(element.search) === -1) { | |
page += element.search; | |
} | |
if (element.hostname !== location.host) { | |
page = "/external/" + element.hostname + page; | |
} | |
track(page); | |
}; | |
clickCallback = function (event) { | |
var page, path, isDoc; | |
if (this.protocol === "mailto:") { | |
// handle mailto links | |
page = "/mailto/" + this.href.substring(7); | |
track(page); | |
} else if (this.hostname === location.host) { | |
// handle document downloads | |
path = this.pathname + this.search; | |
isDoc = path.match(/\.(?:doc|eps|jpg|png|svg|xls|ppt|pdf|xls|zip|txt|vsd|vxd|js|css|rar|exe|wma|mov|avi|wmv|mp3|docx|pptx|xlsx)($|\&|\?)/); | |
if (isDoc) { | |
handleLink(this); | |
} | |
} else if (!this.href.match(/^javascript:/)) { | |
// handle external links | |
handleLink(this); | |
} | |
}; | |
// use event delegation to track clicks. | |
// this makes it possible to track links that are added with AJAX | |
// and has a positive effect on performance, as there is only one eventhandler | |
delegate(document.body, "a", "click", clickCallback); | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment