Skip to content
This repository has been archived by the owner on Apr 27, 2021. It is now read-only.
Yaguang Ding edited this page Jan 13, 2019 · 86 revisions

Chrome Platform Analytics (CPA) is a JavaScript library that lets developers use Google Analytics to measure user interactions in Chrome Platform Apps and Extensions.

Overview

The Google Analytics Platform lets you measure user interactions with your business across various devices and environments. The platform provides resources to collect, store, process, and report on user interactions. Chrome Platform Analytics (CPA) is a client library that lets you collect user interactions specifically in Chrome Platform Apps (also known as Packaged Apps) and Extensions, and send them to the Google Analytics Platform.

Features

The Chrome Platform Analytics (CPA) library:

  • follows the basic usage pattern of Google Analytics and will feel familiar to existing users of Google Analytics;
  • uses an "app-centric" model that is better suited for Chrome Platform Apps and Extensions than the web-centric official Google Analytics JavaScript libraries;
  • provides support for both Closure-based and traditional JavaScript projects;
  • makes it easy to build privacy-friendly apps by providing library-level support for user opt-out; and
  • works when user devices are offline (the library is network-aware and does not cause errors when the network is unavailable).

Setup-Analytics

Refer to Setup using the older Google Analytics Services SDKs

Approach

The Chrome Platform Analytics library generally follows the model established by well-known Google Analytics (GA) tracking libraries, including:

Many of the features you're familiar with in the above libraries are available in the CPA library. The CPA library also provides methods for specific types of hits, such as "event" and "appView". You should use these logical API methods whenever possible – they provide input validation and promote improved readability in your code.

Prerequisites

Before you use the Chrome Platform Analytics library, you should:

API Reference

Namespace

  • analytics - How you access analytics.GoogleAnalytics. Start here.

Classes

  • analytics.GoogleAnalytics - How you access analytics.Tracker and analytics.Config.
  • analytics.Tracker - How you send hits to Google Analytics.
  • analytics.Config - How you inspect and manipulate the runtime configuration.
  • analytics.EventBuilder - An EventBuilder that has the fun-usual property of being immutable...so you can share instaces. Useful if you want to define events in a central location.

How-To

Configure your app

  • The permissions in your app's manifest file, manifest.json, must include permission to communicate with Google Analytics, and also storage permission (required because user-specific settings are stored using Chrome's storage API).

      "permissions": [
        "https://www.google-analytics.com/",
        "storage"
      ],
    
  • If you are using Closure tools, compile the CPA library into your app in the same way that you compile the Closure library or any other third-party Closure-style libraries.

  • If you are not using Closure tools, include google-analytics-bundle.js in your app:

      <script src="google-analytics-bundle.js"></script>
    

Initialize service objects

// If you are using the Closure compiler:
goog.require('analytics.getService');

// You'll usually only ever have to create one service instance.
var service = analytics.getService('ice_cream_app');

// You can create as many trackers as you want. Each tracker has its own state
// independent of other tracker instances.
var tracker = service.getTracker('UA-XXXXX-XX');  // Supply your GA Tracking ID.

Track app view changes

When starting your app, or changing "places" in your app, you should always send an AppView hit. AppView information appears in the "Real-Time" reporting section in Google Analytics reporting for your property.

tracker.sendAppView('MainView');

Track events

Track user actions using an Event. Events have an optional numeric value that is averaged together by Google Analytics.

tracker.sendEvent('Flavor', 'Choose', 'Chocolate');

Custom dimensions & metrics

If you've used custom dimensions & metrics before you know how valuable they can be. But tracker.sendEvent doesn't let you include them when sending an event. To work around this you can compose the event Object yourself and send it using tracker.send, but there's an even better way: analytics.EventBuilder

var FLAVOR_PICKED = analytics.EventBuilder.builder()
    .category('Flavor')
    .action('Choose')
    .dimension(12, 'Custard Based');

// elsewhere...
tracker.send(FLAVOR_PICKED.label('Chocolate'));

Please note that individual analytics.EventBuilder instances are immutable. This is intended to support the centralized definition and reuse of EventBuilder objects. One notable "gotcha" with this pattern is that you can't use an instance like a collector. This won't work:

# NOT SUPPORTED
var event = analytics.EventBuilder.builder();
event.category('Flavor');
event.action('Choose');

// elsewhere...
tracker.send(event);

Nope. event will be empty.

Add privacy support (aka "opt-out")

In order to use Google Analytics (and therefore the CPA library) you must give users notice about analytics tracking and give them the option to opt out of tracking. A user can be opted out of tracking using the setTrackingPermitted(boolean) method on the analytics.Config object. Passing false to this method disables reporting of information to Google Analytics. This setting is persisted across app sessions.

service.getConfig().addCallback(
    /** @param {!analytics.Config} config */
    function(config) {
      var permitted = myApp.askUser('Allow anonymous usage tracking?');
      config.setTrackingPermitted(permitted);
      // If "permitted" is false the library will automatically stop
      // sending information to Google Analytics and will persist this
      // behavior automatically.
    });

See Respecting User Privacy for more information on this topic.

Track events that leave the page/window

Sometimes you want to track a click on a URL that leaves your extension/app, or an event that closes the window. Since events are sent asynchronously, the page may change/close before the event is sent. The event may be sent during your tests, but there's no guarantee. This is particularly important for the popup window of browser actions, which you typically close after a user action. In these cases you can use event callbacks:

tracker.send(allDoneNowHit).addCallback(function() {
  this.closeMe();
}.bind(this));

Another approach is to delegate event sending to the background page, which will run for as long as needed.

Examples

For an illustration of how to use the Chrome Platform Analytics library to measure user interactions, see the example applications.