天天看點

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。

繼續閱讀