Open external link in new window and track outboun

2019-09-06 08:34发布

问题:

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:

  1. 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 ?
  2. 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);
            }
        }
    });
    

    });

回答1:

  1. 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.
  2. 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]);


回答2:

  1. By using the code you have written, all the <a> elements of your site are affected. That should obviously include some links to your own site, except if your site has no menu, which I believe it obviously does.
  2. Maybe you can use jQuery to add a target="_blank" attribute to all your links, after loading the page.