Track all outbound links in Google Analytics

北城余情 提交于 2019-12-02 17:38:31

The reason for the :80 in your output is because of e.currentTarget.host

http://www.w3schools.com/jsref/prop_area_host.asp

I'm not sure why you are tracking that in addition to your already functional url variable, but you can always insure that :80 is not there with a simple string replace

_gat._getTrackerByName()._trackEvent("Outbound Links", e.currentTarget.host.replace(':80',''), url, 0);

Wallace Sidhrée

Fresheyeball answer is the correct one, but because many people have been asking for a complete answer, I'm going to post the final script with Fresheyeball's contribution.

The short version

// Outbound Link Tracking with Google Analytics
// Wallace Sidhrée - http://dreamyguy.com/
// Requires jQuery 1.7 or higher (use .live if using a lower version)
$(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.replace(':80',''), url, 0);
            if (e.metaKey || e.ctrlKey || this.target == "_blank") {
                var newtab = true;
            }
            if (!newtab) {
                e.preventDefault();
                setTimeout('document.location = "' + url + '"', 100);
            }
        }
    });
});

The complete version (commented and 'debug-able')

// Outbound Link Tracking with Google Analytics
// Wallace Sidhrée - http://dreamyguy.com/
// Requires jQuery 1.7 or higher (use .live if using a lower version)
$(function() {
    $("a").on('click',function(e){
        var url = $(this).attr("href");
        // Console logs shows the domain name of the link being clicked and the current window
        // console.log('e.currentTarget.host: ' + e.currentTarget.host);
        // console.log('window.location.host: ' + window.location.host);
        // If the domains names are different, it assumes it is an external link
        // Be careful with this if you use subdomains
        if (e.currentTarget.host != window.location.host) {
            // console.log('external link click');
            // Outbound link! Fires the Google tracker code.
            _gat._getTrackerByName()._trackEvent("Outbound Links", e.currentTarget.host.replace(':80',''), url, 0);
            // Checks to see if the ctrl or command key is held down
            // which could indicate the link is being opened in a new tab
            // Also checks if target="_blank" on the link tag which indicates it should always be opened in a new tab
            if (e.metaKey || e.ctrlKey || this.target == "_blank")) {
                // console.log('ctrl or meta key pressed');
                var newtab = true;
            }
            // If it is not a new tab, we need to delay the loading
            // of the new link for a just a second in order to give the
            // Google track event time to fully fire
            if (!newtab) {
                // console.log('default prevented');
                e.preventDefault();
                // console.log('loading link after brief timeout');
                setTimeout('document.location = "' + url + '"', 100);
            }
        }
        /*
        else {
            console.log('internal link click');
        }
        */
    });
});

The problem with window.open is that the referrer will be lost. A better solution is to use onmousedown instead of onclick. Having done some tests, I know this work better that using window.open or using setTimeout. You got some false positive from people clicking the right mouse button and not choosing "Open in new tab" or "Open in new window", but onclick doesn't always fire for middle and right click on all browser. It's a choice between the lesser of two evils here.

jQuery(function($){
  $('a:not([href*="' + document.domain + '"])').mousedown(function(event){
    // Just in case, be safe and don't do anything
    if (typeof _gat == 'undefined') {
      return;
    }

    var link = $(this);
    var href = link.attr('href');
    var noProtocol = href.replace(/http[s]?:\/\//, '');

    // Track the event
    _gat._getTrackerByName()._trackEvent('Outbound Links', noProtocol);
   });
});

use location.hostname instead of location.host . hostname does not include the port.

This small piece of code worked for me :

    var hostname = window.location.hostname; 

    jQuery("body a").click(function(){

          if(jQuery(this).attr("href").indexOf(hostname)== -1){

               ga('send', 'event', {'eventCategory': "Outbound Links", 'eventAction': "OnClick", 'eventLabel': jQuery(this).attr("href")});

          }
    });

Google has an officially supported library that does this stuff for you.

https://github.com/googleanalytics/autotrack

So your entire Analytics snippet would be something like:

<script>
window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
ga('create', 'UA-XXXXX-Y', 'auto');

// Replace the following lines with the plugins you want to use.
ga('require', 'eventTracker');
ga('require', 'outboundLinkTracker');
ga('require', 'urlChangeTracker');
// ...

ga('send', 'pageview');
</script>
<script async src="https://www.google-analytics.com/analytics.js"></script>
<script async src="path/to/autotrack.js"></script>

Here's my solution using Google suggested code

Put this right after your GA tracking code (probably in <head>)

// TRACK OUTBOUND LINKS
document.addEventListener("DOMContentLoaded", function() {
    var trackOutboundLink = function(url) {
       ga('send', 'event', 'outbound', 'click', url, {
         'transport': 'beacon',
         'hitCallback': function(){document.location = url;}
       });
    }

    var a = document.getElementsByTagName('a');

    for(i = 0; i < a.length; i++){
        if (a[i].href.indexOf(location.host) == -1 && a[i].href.match(/^http?s:\/\//i)){
            a[i].onclick = function(){
                trackOutboundLink(this.href);
            }
        }
    }
});
// END
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!