iscs-analytics
v1.9.0
Published
Analytics wrapper for Google Analytics and Snowplow
Downloads
6
Readme
ISCS Analytics is a Javascript module for logging events to analytics providers (currently Google Analytics and Snowplow). It abstracts differences between analytics providers and allows logging of navigation, errors, timings, conversion, and generic events.
Getting Started
The Analytics module can be loaded as:
- A CommonJS / Node module available as the npm package iscs-analytics
- A
script
tag (creates the global variableAnalytics
when dist/index.js is included on the page)
The library adds Google and Snowplow snippets to the page; these third party snippets should not already be on the page.
API and Examples
The most comprehensive documentation is the set of spec files in the src folder and the ESDocs associated with each public method.
Analytics (constructor)
// in an Angular 1 app (ES5) with the library on window
var analytics = new $window.Analytics({
window: $window,
logger: $log,
appName: 'APP_NAME',
appVersion: 'APP_VERSION',
googleClients: [
{ name: 'iscs', code: 'XXXXXXX' },
{ name: 'client', code: 'YYYYYYY' }
]
});
// in a non-Angular app (with ES2015)
import Analytics from 'iscs-analytics';
const analytics = new Analytics({
window,
appName: 'APP_NAME',
appVersion: 'APP_VERSION',
googleClients: [
{ name: 'iscs', code: 'XXXXXXX' },
{ name: 'client', code: 'YYYYYYY' }
]
});
| Argument | Type | Required | Description / Notes |
| ---------------------- |:--------:|:--------:| ----------------------------------------------------------- |
| appName | string | yes | logged with Google screen analytics and all Snowplow events |
| appVersion | string | yes | logged with Google screen analytics and all Snowplow events |
| window | object | yes | This can be a reference to the browser global window
or to Angular's $window
. It must expose analytics libraries for any logging to happen; missing analytics services will log warnings and be skipped when forwarding events to analytics services. Its location
and document
properties will also be used when logging navigation events. |
| dynamicEventProperties | function | no | Will be invoked on every logging call to find extra properties for logging to unstructured analytics providers (i.e. snowplow). For example: yield an object including user id in a multi-user application; properties that do not change can be moved to constructor arg staticEventProperties
. |
| logger | object | no | Logging library. Can use Angular's $log
or window.console
. If omitted, will default to the console
property of the constructor arg window
. |
| googleClients | object[] | no | An array of google clients in the format [{ name: String, code: String }], e.g. [{ name: 'iscs', code: 'XXXXX' }, { name: 'client', code: 'YYYYYY' }]
. This will cause the window.ga
command to be invoked once per google client, e.g. both window.ga('iscs.send', ...)
and window.ga('client.send', ...)
, instead of window.ga('send', ...)
. At least one client code is required, or no events will be logged to Google. See Google Analytics Creating Trackers |
| logEvents | boolean | no | Whether all events should also be logged to the console; defaults to false but is useful for debugging. Events will be logged with the debug
method on the constructor arg logger
. |
| safeMode | boolean | no | Whether errors (e.g. calling logEvent
with missing parameters) should be logged instead of thrown. Defaults to true. |
| snowplowEndpoint | string | no | Custom endpoint for snowplow tracker; default to the value in config.js. |
| splitTest | string | no | A label for the current split test. If supplied, the Snowplow tracker will be created with a custom context splitTest
for the supplied value. This value will also be the default label for events, conversions, and labels (can be overriden by providing an explicit label
to these methods). |
| staticEventProperties | object | no | Extra properties that do not change and should be logged to unstructured analytics providers (i.e. Snowplow). For example: a build number. |
| trackActivity | boolean | no | Enables snowplow activity tracking (enabled by default, must pass false
to disable). |
| userId | string | no | User id to associate with events (for Snowplow). Can be reset with method setUserId
. |
chaining
All public methods can be chained.
analytics
.logEvent({ category: 'system', action: 'loaded', interaction: false })
.setUserId('[email protected]')
.logNavigation()
.logEvent({ category: 'buy-button', action: 'click' })
.logConversion({ value: 100.5 })
.logNavigation();
Analytics#setUserId
analytics.setUserId('[email protected]')
Sets (or resets) a userId to be associated with events sent to Snowplow.
Analytics#logEvent
See Google Analytics Event Tracking
analytics.logEvent({ category: 'add-to-cart-button', action: 'click', itemId: 4702 });
analytics.logEvent({ category: 'system', action: 'app-loaded', interaction: false });
Properties category
and action
are required; properties label
and value
are optional. Events default to
interactions this can be overriden with interaction: false
. Extra properties may also be specified,
e.g. itemId: 4702
, but these will only be sent to Snowplow (Google will not accept extra parameters).
These events are logged to Google with hitType: 'event'
and Snowplow with type: 'event'
.
The standard properties are category, action, label, property, and value. Google accepts all standard properties
except property
. Providing extra (non-standard) properties will cause the event to be logged to Snowplow as an
unstructured event rather than a structured event; these events will still be sent to Google but the non-standard
properties will not be sent.
If constructor arg splitTest
is set and logging param label
is omitted, label
will default to splitTest
.
Analytics#logConversion
analytics.logConversion({ value: 100.45 });
analytics.logConversion({ label: 'agent-referral', value: 2000, agentId: 42 });
This is a thin wrapper around Analytics#logEvent
. It defaults category
and action
to 'conversion'
.
If constructor arg splitTest
is set and logging param label
is omitted, label
will default to splitTest
.
Analytics#logNavigation
See Google Analytics Page Tracking, Google Analytics App / Screen Tracking, and Snowplow Page Tracking
analytics.logNavigation(); // window.location and window.document details
Logs a navigation event by checking the current state of window (provided to the constructor).
These events are sent to Google as both pageviews and screen analytics; they are sent to Snowplow as pageviews
('trackPageView'
).
Analytics#logTiming
See Google Analytics User Timings
// track time between event and pageload
analytics.logTiming({ category: 'user-interaction', variable: 'first-interaction', value: window.performance.now() });
// track arbitrary span of time
const start = (new Date()).valueOf();
apiCall().then(() => analytics.logTiming({ category: 'customer-api', variable: 'detail-success', value: (new Date().valueOf()) - start }));
Properties category
, variable
and value
are required. Property label
is optional.
If constructor arg splitTest
is set and logging param label
is omitted, label
will default to splitTest
.
Analytics#logError
See Google Analytics Exception Tracking
// to log caught errors
try {
necessaryButRisky();
} catch (e) {
analytics.logError(e);
goToErrorPage(e);
}
// as an async catch
apiCall.then(success, e => analytics.logError(e, false));
// to report invalid states
const error = new Error('invalid app state...');
analytics.logError(error, false);
// shorthand to report invalid states
analytics.logError({ name: 'unexpected-state', message: 'no local storage' }, false);
Logs an error event. This is most effective when used with a default error handler, e.g. window.onerror
,
Redux try / catch middleware, or Angular's $exceptionHandler
factory.
NOTE: logging a fatal error will deactivate logging (additional log calls can be made on the library but they will not be forwarded to Snowplow or Google). This is done because: 1) one fatal error often causes a cascade of other errors 2) future analytics events may be less valid once the application reaches an unanticipated state. To keep analytics enabled, log an error as non-fatal.
| Argument | Type | Required | Default | Description / Notes |
| ------------- |:-------------:|:--------:| ------- | ----------------------------------------------- |
| error | Error|object | yes | | a collection of properties describing the error |
| error.name | string | yes | | name of the error (for native Error objects this will be the prototype name, probably 'Error') |
| error.stack | string | no | ''
| a stack trace from when the error was created (populated by the native Error constructor) |
| error.message | string | no | ''
| the error message (for Error objects, this is the string passed to the Error constructor) |
| fatal | boolean | no | true
| whether the error is irrecoverable |
Status
This library is a work in progress; it is still missing some functionality from its previous implementation (e.g. Google clients cannot be independently configured).