天天看点

google analytics 跟踪出站链接

添加gtag.js

首先将gtag.js添加至网站的

<head></head>

之间

<script async src="https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'GA_MEASUREMENT_ID');
</script>
           

将GA_MEASUREMENT_ID替换为Google Analytics(分析)媒体资源的 ID.

跟踪脚本

将以下代码添加至html

<script>
/**
* Google Analytics(分析)中的函数,跟踪对出站链接的点击。
* 此函数会将有效网址字符串作为参数,并将该网址字符串
* 用作事件标签。通过将 transport 方法设置为“beacon”来发送命中
* 在支持“navigator.sendBeacon”的浏览器中使用该方法。
*/
var trackOutboundLink = function(url) {
  gtag('event', 'click', {
    'event_category': 'outbound',
    'event_label': url,
    'transport_type': 'beacon',
    'event_callback': function(){document.location = url;}
  });
}
</script>
           

Google 的文档详细描述了不同参数的功能,感兴趣的同学可以去查看。

然后在需要跟踪的元素中使用该脚本

<a href="http://www.example.com" target="_blank" rel="external nofollow"  onclick="trackOutboundLink('http://www.example.com'); return false;">查看 example.com</a>
           

至此,当用户点查看 example.com, gtag.js就会发送该点击事件给到google analytics,相应的event_category是:outbound。

继续阅读