プラグインは、analytics.js の機能を強化して、問題解決とユーザー インタラクションの測定をサポートするためのスクリプトです。このガイドでは、独自の analytics.js プラグインを作成する手順について説明します。analytics.js プラグインを各実装で使用する方法の詳細については、プラグインを使用するをご覧ください。
プラグインを定義する
プラグインは provide
コマンドで定義します。このコマンドは、1 つ目の引数でプラグインの名前、2 つ目の引数でプラグインのコンストラクタ関数を指定して呼び出します。provide
コマンドを実行すると、使用するプラグインが ga()
コマンドキューに登録されます。
プラグイン コンストラクタ
最も基本的な anlytics.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
コマンドが実行されると、new
演算子を使用して、provide
で指定したプラグインのコンストラクタ関数で新しいオブジェクトがインスタンス化されます。コンストラクタには、1 つ目の引数としてトラッカー オブジェクトが渡され、require
コマンドに渡されたすべての設定オプションが、2 つ目の引数として渡されます。
Google アナリティクス タグに、次のように 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', ...)
コマンドが 3 秒後に実行されるまで 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);
例
次に示すのは、ページの URL からカスタム キャンペーンの値を取得してトラッカーに渡すプラグインの例です。この例では、プラグイン スクリプトの定義と登録を行う方法、プラグインの設定パラメータを渡す方法、プラグイン メソッドを定義して呼び出す方法を確認できます。
// 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>
自動トラッキング機能プラグイン
自動トラッキング機能ライブラリは、GitHub が提供するオープンソースのライブラリで、一般的なユーザー インタラクションをトラッキングするための analytics.js 用プラグインが含まれています。プラグインの動作について詳しくは、自動トラッキングのソースコードをご覧ください。