问题
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:
- 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 ?
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:
- 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 (likewww.domain.com
) but have some links without it (likedomain.com/link.html
), they'd be considered an external link. - 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 withhttp://
orhttps://
. This should be include all outbound links..not('[href*="mydomain.com"]')
-- throw out any links containingmydomain.com
, just in case there are any internal links that start withhttp://
...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:
- 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. - Maybe you can use jQuery to add a
target="_blank"
attribute to all your links, after loading the page.
来源:https://stackoverflow.com/questions/15121582/open-external-link-in-new-window-and-track-outbound-click-event