編寫外掛程式

外掛程式是強化 analytics.js 功能的指令碼,可協助解決問題,並協助評估使用者互動。本指南說明自行編寫 analytics.js 外掛程式的程序。如要瞭解如何在自己的導入作業中使用 analytics.js 外掛程式,請參閱「使用外掛程式」一文。

定義外掛程式

外掛程式是透過 provide 指令定義,如要叫用該外掛程式,您必須使用外掛程式名稱做為第一個引數,後面接著外掛程式的建構函式函式。執行 provide 指令時,外掛程式會透過 ga() 指令佇列註冊要使用的外掛程式。

外掛程式建構函式

以下是 analytics.js 外掛程式的最基本範例:

// Defines the plugin constructor.
function MyPlugin() {
  console.log('myplugin has been required...');
}

// Registers the plugin for use.
ga('provide', 'myplugin', MyPlugin);

即使全域 ga 物件已重新命名,外掛程式仍必須正確運作,因此,如果您要編寫供第三方使用的外掛程式,則應納入檢查項目,確認 GoogleAnalyticsObject 變數是否已設為 'ga' 以外的字串。以下 providePlugin 函式會執行這項作業:

// Provides a plugin name and constructor function to analytics.js. This
// function works even if the site has customized the ga global identifier.
function providePlugin(pluginName, pluginConstructor) {
  var ga = window[window['GoogleAnalyticsObject'] || 'ga'];
  if (typeof ga == 'function') {
    ga('provide', pluginName, pluginConstructor);
  }
}

設定外掛程式執行個體

ga() 指令佇列執行 require 指令時,會針對 provide 外掛程式的建構函式函式使用 new 運算子,將新物件執行個體化。建構函式會將追蹤器物件做為第一個引數傳遞,然後將傳遞至 require 指令的任何設定選項做為第二個引數傳遞。

建議在 Google Analytics (分析) 代碼中加入下列 require 指令:

ga('create', 'UA-XXXXX-Y', 'auto');
ga('require', 'localHitSender', {path: '/log', debug: true});
ga('send', 'pageview');

以及 localHitSender 程式碼:

function LocalHitSender(tracker, config) {
  this.path = config.path;
  this.debug = config.debug;
  if (this.debug) {
    console.log('localHitSender enabled for path: ' + this.path);
    console.log('on tracker: ' + tracker.get('name'));
  }
}

providePlugin('localHitSender', LocalHitSender);

執行 require 指令時,系統會將下列項目記錄至控制台 (請注意,預設追蹤程式的名稱為「t0」):

// localHitSender enabled for path: /log
// on tracker: t0

定義外掛程式方法

外掛程式可公開自己的方法,您可以使用 ga 指令佇列語法叫用這些方法:

ga('[trackerName.]pluginName:methodName', ...args);

其中 trackerName 為選用項目,methodName 則對應外掛程式建構函式原型上的函式名稱。如果外掛程式上沒有 methodName,或是外掛程式不存在,就會發生錯誤。

外掛程式方法呼叫範例:

// Execute the 'doStuff' method using the 'myplugin' plugin.
ga('create', 'UA-XXXXX-Y', 'auto');
ga('require', 'myplugin');
ga('myplugin:doStuff');

// Execute the 'setEnabled' method of the 'hitCopy' plugin on tracker 't3'.
ga('create', 'UA-XXXXX-Y', 'auto', {name: 't3'});
ga('t3.require', 'hitcopy');
ga('t3.hitcopy:setEnabled', false);

外掛程式方法定義範例:

// myplugin constructor.
var MyPlugin = function(tracker) {
};

// myplugin:doStuff method definition.
MyPlugin.prototype.doStuff = function() {
  alert('doStuff method called!');
};

// hitcopy plugin.
var HitCopy = function(tracker) {
};

// hitcopy:setEnabled method definition.
HitCopy.prototype.setEnabled = function(isEnabled) {
  this.isEnabled = isEnabled;
}:

正在載入外掛程式

外掛程式通常會從單獨的 JavaScript 檔案載入,或是隨附於您的主要應用程式程式碼。

<script async src="myplugin.js"></script>

但不一定要事先定義。由於 analytics.js 是以非同步方式載入,外掛程式通常也是以非同步方式載入,因此建構 ga() 指令佇列可以處理這種情況。

如果指令佇列收到尚未提供的外掛程式 require 指令,則在外掛程式可供使用之前,系統將暫停執行佇列中的其餘項目。

下列程式碼說明在遇到 ga('provide', 'myplugin', ...) 指令三秒後,實際上如何執行 ga('require', 'myplugin') 指令。

ga('require', 'myplugin');

function MyPlugin() {
  console.log('myplugin has been required...');
}

// Waits 3 second after running the `require`
// command before running the `provide` command.
setTimeout(function() {
  ga('provide', 'myplugin', MyPlugin);
}, 3000);

示例

以下範例外掛程式可從網頁網址擷取自訂廣告活動值,並將這些值傳送到追蹤程式。這個外掛程式示範如何定義及註冊外掛程式指令碼、傳送外掛程式設定參數,以及定義及呼叫外掛程式方法。

// campaign-loader.js

function providePlugin(pluginName, pluginConstructor) {
  var ga = window[window['GoogleAnalyticsObject'] || 'ga'];
  if (typeof ga == 'function') {
    ga('provide', pluginName, pluginConstructor);
  }
}

/**
 * Constructor for the campaignLoader plugin.
 */
var CampaignLoader = function(tracker, config) {
  this.tracker = tracker;
  this.nameParam = config.nameParam || 'name';
  this.sourceParam = config.sourceParam || 'source';
  this.mediumParam = config.mediumParam || 'medium';
  this.isDebug = config.debug;
};

/**
 * Loads campaign fields from the URL and updates the tracker.
 */
CampaignLoader.prototype.loadCampaignFields = function() {
  this.debugMessage('Loading custom campaign parameters');

  var nameValue = getUrlParam(this.nameParam);
  if (nameValue) {
    this.tracker.set('campaignName', nameValue);
    this.debugMessage('Loaded campaign name: ' + nameValue);
  }

  var sourceValue = getUrlParam(this.sourceParam);
  if (sourceValue) {
    this.tracker.set('campaignSource', sourceValue);
    this.debugMessage('Loaded campaign source: ' + sourceValue);
  }

  var mediumValue = getUrlParam(this.mediumParam);
  if (mediumValue) {
    this.tracker.set('campaignMedium', mediumValue);
    this.debugMessage('Loaded campaign medium: ' + mediumValue);
  }
};

/**
 * Enables / disables debug output.
 */
CampaignLoader.prototype.setDebug = function(enabled) {
  this.isDebug = enabled;
};

/**
 * Displays a debug message in the console, if debugging is enabled.
 */
CampaignLoader.prototype.debugMessage = function(message) {
  if (!this.isDebug) return;
  if (console) console.debug(message);
};

/**
 * Utility function to extract a URL parameter value.
 */
function getUrlParam(param) {
  var match = document.location.search.match('(?:\\?|&)' + param + '=([^&#]*)');
  return (match && match.length == 2) ? decodeURIComponent(match[1]) : '';
}

// Register the plugin.
providePlugin('campaignLoader', CampaignLoader);

上述程式碼可加入 HTML 網頁,如下所示:

<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-XXXXX-Y', 'auto');
ga('require', 'campaignLoader', {
  debug: true,
  nameParam: 'cname',
  sourceParam: 'csrc',
  mediumParam: 'cmed'
});
ga('campaignLoader:loadCampaignFields');

ga('send', 'pageview');
</script>

<!--Note: plugin scripts must be included after the tracking snippet. -->
<script async src="campaign-loader.js"></script>

自動追蹤外掛程式

autotrack 程式庫是 GitHub 提供的開放原始碼,並包含數個 analytics.js 外掛程式,可協助追蹤常見使用者互動。請參閱自動追蹤原始碼,進一步瞭解外掛程式的運作方式。