플러그인 작성

플러그인은 문제를 해결하고 사용자 상호작용을 측정하는 데 도움이 되도록 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 애널리틱스 태그에 다음과 같은 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;
}:

플러그인 로드

플러그인은 일반적으로 별도의 자바스크립트 파일에서 로드되거나 기본 애플리케이션 코드와 함께 번들로 제공됩니다.

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

요청하기 전에 플러그인을 정의할 필요는 없습니다. analytics.js가 비동기식으로 로드되고 플러그인도 종종 비동기식으로 로드되므로 ga() 명령어 큐는 이를 처리하도록 빌드됩니다.

명령어 큐는 아직 제공되지 않은 플러그인의 require 명령어를 수신하는 경우 플러그인을 사용할 수 있을 때까지 큐에 있는 나머지 항목의 실행을 중지합니다.

다음 코드는 3초 후 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);

다음은 페이지 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>

Autotrack 플러그인

autotrack 라이브러리는 GitHub에서 이용할 수 있는 오픈소스로 일반적인 사용자 상호작용을 추적하는 데 도움이 되는 analytics.js 플러그인이 포함되어 있습니다. 플러그인의 작동 방식을 자세히 알아보려면 autotrack 소스 코드를 참고하세요.