Here's a modified snippet from the link you provided that should work both for links that open in the current window and links that open in a new window without any modification:
<script type="text/javascript">
// Records an event for an outbound link. Supports links even if they open in a
// different window (target="_blank").
// Don't forget to return the return value of this function from the onclick handler.
// link - A reference to the <a> anchor object to which this call is attached
// parameters - Parameters to pass to the event, in an array:
// category/action/label/value/noninteraction or some subset; see GA docs.
// Pass "undefined" (the value, not the string) for unspecified optional params if necessary.
// Exmaple:
// <a href="http://www.google.com"
// onclick="return recordOutboundLink(this, ['category', 'action', 'label', 6.6, false);">link</a>
function recordOutboundLink(link, parameters) {
try {
_gaq.push(['_trackEvent'].concat(parameters));
if (link.target == '_blank') {
return true;
} else {
setTimeout(function() { document.location = link.href }, 100);
return false;
}
} catch (err) {
return true;
}
}
</script>
Here are the two link types. Note that the onclick handler is the same in both:
<a href="http://www.example.com"
onClick="return recordOutboundLink(this, ['Outbound Links', 'example.com']);">
<a href="http://www.example.com"
target="_blank"
onClick="return recordOutboundLink(this, ['Outbound Links', 'example.com']);">
Limitations:
- If the browser ignores the 'target="blank"' and instead opens the URL in the same window (e.g. a UIWebView inside the Facebook iOS app), then the link may not get tracked. This is also true of ErikdR's accepted answer. You can add code to detect cases like this (e.g. detect ipad/iphone webview via javascript).
- If the user tries to ctrl-/shift-/cmd-click (i.e. open in a new tab or window) a link that doesn't have 'target="blank"', the URL will open in the existing window rather than opening in a new window. The same is true of Roslyn's code snippet (and Google's official code sample). Again, you can add code to handle these special cases.