1

I'm trying to work with another companies google analytics code. Unfortunately I don't have much experience with it and only understand the basics of the code.

The following code I'm working with should be tracking cross browser clicks: (I've cut out most of the code and written the important pieces)

if (($(link).attr('href').indexOf('example.com') != -1) && 
         (window.location.href.indexOf('example.com') == -1)) {
  $(link).bind('click', function (l) {
    if (typeof (_gat) == "object") {
      l.preventDefault();
      _gaq.push(['_link', $(link).attr('href')]);
    }
  });
}

Now the issue i'm encountering is the prevent default is now block all the external links from opening in a new window.

How can I modify this code and maintain the tracking so they still do?

Greg B
  • 803
  • 9
  • 22
  • How did you get to the conclusion that google analytics is blocking it? – MilkyWayJoe Apr 24 '12 at 14:43
  • 1
    l.preventDefault() is stopping the regular anchor behavior and _gaq.push is doing the page redirection. When I comment it out, both a new window and the same window go to the new page – Greg B Apr 24 '12 at 14:46
  • I'm not sure that `_gaq.push` does a redirect. I think you have to manually set the `window.location` to the url *after* you add the tracking info to google analytics.. have you seen this question http://stackoverflow.com/questions/8692503/javascript-redirect-with-google-analytics ? – MilkyWayJoe Apr 24 '12 at 15:13
  • Actually you're right, the anchor is still doing the page redirection but the preventdefault in the code removes the target="_blank" functionality. – Greg B Apr 24 '12 at 15:25

1 Answers1

2

_link set's location.href internally to jump to the new URL, but ignores any target attributes in the link. Instead of using _link, you can use _getLinkerUrl and follow the URL yourself

$(link).bind('click', function (l) {
  if (typeof (_gat) == "object") {
      var pageTracker = _gat._getTrackerByName();
      var url = pageTracker._getLinkerUrl(this.href);
      l.preventDefault();
      if ($(this).attr('target') != '_blank') location.href = url;
      else window.open(url);
  }
});
mike
  • 7,137
  • 2
  • 23
  • 27