I am using the code below to track outbound links in google analytics ( found it somewhere on this site ). I have 2 issues coming up:
- Sometimes, the e.currentTarget.host part of the output shows my own domain - instead of showing the domain where the click leads to. Any idea why my domain shows up on occasion ?
Is it possible to modify this code to do the following (1) force link to open in new window and (2) track the outbound click event as shown.
$(function() {
$("a").on('click',function(e){
var url = $(this).attr("href");
if (e.currentTarget.host != window.location.host) {
_gat._getTrackerByName()._trackEvent("Outbound Links", e.currentTarget.host, url, 0);
if (e.metaKey || e.ctrlKey) {
var newtab = true;
}
if (!newtab) {
e.preventDefault();
setTimeout('document.location = "' + url + '"', 100);
}
}
});
});
- The code compares the domain in the link with the window domain:
e.currentTarget.host != window.location.host
-- If your domain has a www prefix (like www.domain.com
) but have some links without it (like domain.com/link.html
), they'd be considered an external link.
- The original code uses a delay before setting document.location to allow time for the _trackEvent's tracking request. Since you want all off-site links to open in a new window, the delay can be eliminated.
The following code should work regardless of any www or sub-domain prefix:
jQuery(function($) {
$('a[href^="http://"],a[href^="https://"]')
.not('[href*="mydomain.com"]')
.click(function(e) {
var url = this.href;
_gat._getTrackerByName()._trackEvent("Outbound Links", e.currentTarget.host, url, 0);
e.preventDefault();
window.open(url);
})
});
$('a[href^="http://"],a[href^="https://"]')
-- select links that start with http://
or https://
. This should be include all outbound links.
.not('[href*="mydomain.com"]')
-- throw out any links containing mydomain.com
, just in case there are any internal links that start with http://
...
e.preventDefault();
-- prevent link from being followed normally.
Also, if you're using the current, asynchronous Google Analytics code, you can shorten the _trackEvent call to
_gaq.push(['_trackEvent', 'Booking', "Outbound Links", e.currentTarget.host, url, 0]);