带重定向的出站链接追踪:如何修改Google Analytics脚本实现追踪
解决Google Analytics追踪被跳转修改后的出站链接问题
没问题,完全可以修改你的Analytics脚本,继续追踪这类被Amazon Link Localizer插件修改后的出站链接点击。核心思路是从跳转URL(prourls.com?url=xxx)里提取出真实的目标链接,然后把这个真实地址作为GA事件的标签发送,同时保持正常的跳转行为。
具体修改方案
假设你原本的出站链接追踪脚本是监听页面内的点击事件,判断是否为外部链接后发送GA事件。现在只需要在逻辑里增加对prourls跳转链接的解析处理:
方案1:使用现代JS的URLSearchParams解析(推荐)
如果你的网站不需要兼容非常老旧的浏览器(比如IE11及以下),可以用URLSearchParams直接提取url参数的值:
document.addEventListener('click', function(e) { // 找到被点击的<a>标签 const targetLink = e.target.closest('a'); if (!targetLink) return; // 先处理prourls的跳转链接 if (targetLink.host === 'prourls.com') { const params = new URLSearchParams(targetLink.search); const realOutboundUrl = params.get('url'); if (realOutboundUrl) { e.preventDefault(); // 发送GA事件,用真实的目标链接作为标签 gtag('event', 'click', { 'event_category': 'Outbound Links', 'event_action': 'click', 'event_label': decodeURIComponent(realOutboundUrl), // 解码URL编码的地址 'transport_type': 'beacon', // 确保事件在页面跳转前发送完成 'hitCallback': function() { window.location = targetLink.href; // 跳转到原跳转链接 } }); return; } } // 处理普通的出站链接(保持原有逻辑) if (targetLink.host !== window.location.host) { e.preventDefault(); gtag('event', 'click', { 'event_category': 'Outbound Links', 'event_action': 'click', 'event_label': targetLink.href, 'transport_type': 'beacon', 'hitCallback': function() { window.location = targetLink.href; } }); } });
方案2:用正则解析(兼容老旧浏览器)
如果需要兼容IE等不支持URLSearchParams的浏览器,可以用正则表达式提取真实链接:
document.addEventListener('click', function(e) { const targetLink = e.target.closest('a'); if (!targetLink) return; if (targetLink.host === 'prourls.com') { // 匹配url参数的值 const urlMatch = targetLink.href.match(/url=([^&]+)/); if (urlMatch && urlMatch[1]) { const realOutboundUrl = decodeURIComponent(urlMatch[1]); e.preventDefault(); ga('send', 'event', 'Outbound Links', 'click', realOutboundUrl, { 'transport': 'beacon', 'hitCallback': function() { window.location = targetLink.href; } }); return; } } // 普通出站链接处理 if (targetLink.host !== window.location.host) { e.preventDefault(); ga('send', 'event', 'Outbound Links', 'click', targetLink.href, { 'transport': 'beacon', 'hitCallback': function() { window.location = targetLink.href; } }); } });
关键注意事项
- 解码URL:因为插件生成的
url参数值通常是URL编码过的,所以要用decodeURIComponent还原真实地址,避免GA里记录的是乱码或编码后的字符串。 - 测试验证:修改后可以用Google Analytics的实时报告(实时>事件),点击Amazon链接后查看事件标签是否是真实的
www.amazon.com地址。 - 灵活调整判断条件:如果插件生成的跳转域名不是
prourls.com,记得修改targetLink.host === 'xxx.com'的判断值。
内容的提问来源于stack exchange,提问作者zgall1
相关产品推荐
相关产品推荐

