在新窗口中打开外部链接并跟踪出站点击事件
我使用下面的代码来跟踪谷歌分析中的出站链接(在这个网站的某个地方找到它)。 我有两个问题:
- 有时,输出的e.currentTarget.host部分显示我自己的域 – 而不是显示点击所在的域。 知道我的域名有时出现的原因吗?
-
是否可以修改此代码以执行以下操作(1)强制链接在新窗口中打开,以及(2)跟踪出站点击事件,如图所示。
$(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); } } });
});
- 代码将链接中的域与窗口域进行比较:
e.currentTarget.host != window.location.host
– 如果您的域名具有www前缀(如www.domain.com
),但没有它的某些链接(如domain.com/link.html
),它们被视为外部链接。 - 原始代码在设置document.location之前使用延迟,以便为_trackEvent的跟踪请求留出时间。 由于您希望在新窗口中打开所有场外链接,因此可以消除延迟。
无论任何www或子域前缀如下,以下代码都应该有效:
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://"]')
– 选择以http://
或https://
开头的链接。 这应该包括所有出站链接。 -
.not('[href*="mydomain.com"]')
– 抛出包含mydomain.com
任何链接,以防万一有以http://
开头的内部链接… -
e.preventDefault();
– 防止链接正常进行。
此外,如果您使用当前的异步Google Analytics代码,则可以缩短_trackEvent调用
_gaq.push(['_trackEvent', 'Booking', "Outbound Links", e.currentTarget.host, url, 0]);