Captain Codeman Captain Codeman

Google Analytics for Polymer Single Page Apps

How to track page views with a Polymer SPA

Contents

Introduction

Just a quick snippet for integrating Google Analytics with Polymer Single Page Apps.

As well as tracking ‘page’ views anytime the route changes, it also uses Google Analytic’s Exception Tracking feature for cheap-as-chips error reporting - handy to check on any browser compatibility issues you might have missed.

In the <head>:

<script>
  (function() {
    'use strict';

    if (location.hostname === 'localhost') return;

    window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;

    ga('create', 'UA-PROPERTYID', 'auto');

    window.addEventListener('app-metadata', function(e) {
      ga('set', 'page', location.pathname);
      ga('send', 'pageview');
    });

    window.addEventListener('error', function(e) {
      ga('send', 'exception', {
        'exDescription': e.message,
        'exFatal': false
      });
    });
    window.addEventListener('WebComponentsReady', function(e) {
      if (window.performance) {
        ga('send', 'timing', 'JS Dependencies', 'WebComponentsReady', Math.round(performance.now()));
      }
    });
  })();
</script>

The analytics script itself is loaded asynchronously in the <body> at the bottom so it’s lower-priority than the app itself:

<script src="https://www.google-analytics.com/analytics.js" async></script>

I’m listening for the app-metadata event that my app-metadata element uses to update the page title and description but you could listen for any other appropriate app-route or location event - whatever indicates “the page has changed” within your app.

I also disable tracking for localhost because I don’t want my dev-views or script errors cluttering up the logs.