Analytics.js for Web

Overview

This guide will cover how to implement the Analytics.js SDK for MetaRouter and begin sending events into your MetaRouter cluster from your website. This is the easiest MetaRouter install and can generally be completed in minutes, assuming you have already created your Data Infrastructure.

Installing the SDK

Once the snippet is placed on your website within the <head> tag, you will be ready to trigger events from your website:

<script type='text/javascript'>
!(function() {
  var analytics = (window.analytics = window.analytics || [])
  if (!analytics.initialize) {
    if (analytics.invoked) {
      window.console && console.error && console.error('MetaRouter snippet included twice.')
    } else {
      analytics.invoked = !0
      analytics.methods = [
        'trackSubmit',
        'trackClick',
        'trackLink',
        'trackForm',
        'pageview',
        'identify',
        'reset',
        'group',
        'track',
        'ready',
        'alias',
        'debug',
        'page',
        'once',
        'off',
        'on',
        'addSourceMiddleware',
        'addIntegrationMiddleware',
        'setAnonymousId',
        'addDestinationMiddleware',
      ]
      analytics.factory = function(e) {
        return function() {
          var t = Array.prototype.slice.call(arguments)
          t.unshift(e)
          analytics.push(t)
          return analytics
        }
      }
      for (var e = 0; e < analytics.methods.length; e++) {
        var key = analytics.methods[e]
        analytics[key] = analytics.factory(key)
      }
      analytics.load = function(key, e) {
        var t = document.createElement('script')
        t.type = 'text/javascript'
        t.async = !0
        t.src = ("https:"===document.location.protocol?"https://":"http://")+"YOUR_CDN_URL"+key+".js.gz"
        var n = document.getElementsByTagName('script')[0]
        n.parentNode.insertBefore(t, n)
        analytics._loadOptions = e
      }
      analytics.SNIPPET_VERSION = '4.13.1'
      analytics.load("YOUR_WRITE_KEY")
      analytics.page()
    }
  }
})()
</script>

Note that there are two edits you need to make to the above snippet:

  • Your CDN URL, which is where the analytics.js file the snippet calls to is located. You will need to determine your preferred DNS settings prior to setting the CDN URL and adding the snippet. Please see this guide for more information.
  • Your writeKey, which will be determined as a part of your MetaRouter cluster setup.

Default Page Events

The snippet above includes the analytics.page() function, which will automatically trigger Page calls. You can remove this function from the snippet if you do not want to trigger Page calls on every webpage loaded on your website. We recommend leaving this function in the snippet in most cases.

Considerations for Self-Hosting CDN files
We recommend hosting the Analytics.js file within your own CDN in order to receive the maximum 1st Party benefits from our platform.

You will be provided a custom-built version of this SDK that is GZIP compressed. To maintain this compression, which minimizes the page load time, you will need to set the following Metadata on the SDK within your CDN if it does not do so automatically.

On the Upload window, add the following Metadata

TypeKeyValue
System DefinedContent-Encodinggzip
System DefinedContent-Typeapplication/javascript

Analytics.js for Web Event Methods

With the following events, you can track almost any kind of action being taken and consistently identify the users on your website. Check out each event type below to learn more about when to trigger them and what to include with each event.

Analytics.js & Cookies

The Analytics.js library places identifiers in the form of first-party cookies on the browser that are persisted between user sessions. The library will always create the ajs_anonymous_id cookie if that cookie is not already present, and will create the ajs_user_id cookie only if an identify call is made. If one of these cookies is cleared, the value is also saved as a backup on the browser's Local Storage, allowing for the value to be restored if the user deletes their cookies. Both cookies will expire after one year, unless browser restrictions cause cookies to expire within a shorter timeframe.

Advanced Patterns

Custom Consent Banner / Opt-In Tracking Compliance

While the SDK will queue up events for process, it will not send those events from the browser until the analytics.load(...) function is called. Typically, we recommend placing this within the initialization snippet that loads the full library, however, it is not required to exist there and be triggered once the full library is loaded.

Instead, to leverage this functionality in order to control if events are allowed to be sent, you can trigger this analytics.load(...) after any custom functionality you need.

For example, if we want to allow the user to agree to be tracked before any events are sent, we'd remove analytics.load from the initialization snippet and tie its trigger to the agree button on your custom consent banner. Since the events queued for delivery will not send until the load function is called, once the user navigates away from the page those events will be purged from their browser.

Keep in mind that you will need additional functionality to remember the user's preference and either inhibit the load function or remove the initialization snippet upon further page visits, as the Javascript SDK will not keep track of any preferences regarding opt-in consent on its own.

Providing Consent Preferences

You can forward consent categories to the MetaRouter platform to ensure that those requests can be respected during the server-side processing of events.

By default, our AJS file will look for a cookie called OptOutOnRequest but the name can be customized within the AJS Builder settings. Also, within the Builder settings, you can set the default consent values to be implicit (CCPA-mode, default) requiring categories to be opted out of or explicit (GDPR-mode) requiring categories to be opted into before consent is assumed.

The consent category values are based off on the OneTrust banner standards, and we expect the cookie value to be within the following format: groups=C0004:1,C0002:1,C0001:1,C0003:1,C0005:1

Encoded within the document.cookie it should translate to the following:

OptOutOnRequest=groups=C0004%3A1%2CC0002%3A1%2CC0001%3A1%2CC0003%3A1%2CC0005%3A1

The cookie should be set before analytics.load() is triggered, however if consent needs to be updated after load, then those preferences can be updated by firing analytics.refreshCompliance() once new compliance categories are updated within the cookie.

Single Page Application (SPA) Snippet Initialization

The default initialization snippet, which loads the full Javascript SDK, recommends having both analytics.load(...) and analytics.page() triggered inside of it.

For Single Page Applications, it is best to remove analytics.page() from here and trigger it as part of your page routing logic for your application. Depending on your application configuration, you may need to specify window.analytics.page() to ensure your function call is triggered within the correct context.

Utility Functions

Options

Allows you to disable the sending to MetaRouter on a per-event basis, as well as any client-side tag that MetaRouter manages. If needed, the structure is as follows: { integrations: { 'All': true, 'metarouter': false } If using the Callback argument, you must provide an Options argument however that argument can simply be an empty object: {} .

Callback

This allows you to chain an additional function to be triggered after the request of the event is finished or is timed out.

Other Functions

  • analytics.debug(true) - Running this command within your browser console and refreshing the page will pretty-print all actions a.js takes into your browser’s console. Handy to understand the logic being performed and the event payloads without having to filter network activity or leverage browser extensions. Alternatively, run localStorage.setItem('debug', 'analytics:*') to keep the debug mode alive between pages and page reloads
  • analytics.ready() - The argument for this function will take a function and execute it once a.js is finished initializing and is actively sending events.
  • analytics.on(method, callback) - This is an event emitter function that allows you to tap into the event stream and run a callback function if a certain type of event happens. An example of this logic is below: track', function(event, properties, options) { bigdataTool.push(['recordEvent', event]); }
  • analytics.setAnonymousId('ABC-123-XYZ') - This function allows you to override the default Anonymous ID that MetaRouter sets for all unknown users. Helpful for when you have a preferred ID for users you prefer all downstream vendors to know about, but does not treat it as a known ID like the identify method would