I have a bunch of links that use a target="_blank" attribute to open in a new window. I want to attach Google Analytics goal tracking to clicks of these links.
To do this, I tried attaching an onclick="pageTracker._trackPageview('/event/outgoing')" attribute to the links.
But I discovered that for links with a target="_blank" attribute, the Javascript onclick event gets skipped. So the goal is not recorded. In other words, this link successfully records the goal:
<a href="http://www.yahoo.com" onclick="pageTracker._trackPageview('/event/outgoing')">Click me</a>
But this does not:
<a href="http://www.yahoo.com" target="_blank" onclick="pageTracker._trackPageview('/event/outgoing')">Click me</a>
Does anyone know why this might be occurring? Assuming there isn't an easy solution, I assume I'll have to use Javascript to solve the problem. The following code successfully records a goal (but does not open the link):
function attach_goal_tracking() {
var links = document.getElementsByClassName("buyTicketsLink");
for(var i=0; i<links.length; i++) {
links[i].onclick = record_goal;
}
}
function record_goal(e) {
e.stop();
pageTracker._trackPageview('/event/outgoing');
}
But when I add to the record_goal function to open the link...
function record_goal(e) {
e.stop();
pageTracker._trackPageview('/event/outgoing');
var newWindow = window.open(this.getAttribute('href'), '_blank');
newWindow.focus();
}
...then it fails to track the goal.
Can anyone tell me why this might be, and what I should do to get around this problem? FYI I'm using Prototype for Javascript.
There might be an issue with popup blockers (I'm thinking Googlebar) stopping the window from opening, and (with the presence of
onclick
) preventing theonclick
code from running. For example see this and this similar sounding issues other people are having.Or it might simply be that the click handler code is throwing an error that then prevents the rest of the code from completing. See my comment to your question re how you are binding the events.
e.stop()
may be failing in IE.Your hypothesis however is false.
target="_blank"
andonclick="..."
do work together just fine.Testcase in point: http://jsbin.com/anahe (add
/edit
to the url to edit the code). You may need to turn off your popup blocker(s):Clicking on the link opens a new window and updates the div with the number of times the linked has been clicked. Tested this in IE6, IE7, FF2, FF3.5, Chrome 2, Chrome 3, Opera 9.
It is possible, victor is right the e.stop() is uneccessary, I can confirm that the following code successfully opens a new tab, and asynchronously alerts on the old tab (consequently making it regain focus).
The next best thing is to have a link tracking page and route all your external links through that page.