Posted over 2 years ago. Visible to the public.

Using Google Analytics with Unpoly

The default Google Analytics might not work as expected with your Unpoly app. This is because your app only has a single page load when the user begins her session. After that only fragments are updated and the <script> tag that sends the page view to Google Analytics is probably never evaluated again.

Luckily you can fix this.

Simple mode: You just want to track all the page views

Embed your Google Analytics code as always.

Now add the following code snippet:

Copy
up.on('up:history:pushed', function(event) { ga('set', 'page', location.pathname); ga('send', 'pageview'); });

Hard mode: You want more control over what's being tracked

First, edit your Google Analytics code snippet and comment out the last line (ga('send', 'pageview')):

Copy
<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','https://www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-1234567', 'auto'); // ga('send', 'pageview'); // Don't send the pageview here </script>

Now add the following compiler:

Copy
up.compiler('[track-for-analytics]', function($element) { var url = $element.attr('track-for-analytics') || location.pathname; ga('set', 'page', url); ga('send', 'pageview'); });

Finally look for containers that represent trackable content, and give them the track-for-analytics attribute:

Copy
<div class="page" track-for-analytics> ... </div>

If you want to track something else than the current URL (e.g. if the URL contains a secret) you can set the attribute value to a custom URL:

Copy
<div class="page" track-for-analytics="/other-url"> ... </div>

makandra has been working exclusively with Ruby on Rails since 2007. Our laser focus on a single technology has made us a leader in this space.

Owner of this card:

Avatar
Henning Koch
Last edit:
about 2 years ago
by Henning Koch
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more