Posted about 6 years ago. Visible to the public.

Using Google Analytics with Unpoly

The default Google Analytics might not work as expected with your Unpoly Archive 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:

up.on('up:location:changed', 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')):

<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','','ga'); ga('create', 'UA-1234567', 'auto'); // ga('send', 'pageview'); // Don't send the pageview here </script>

Now add the following compiler:

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:

<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:

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

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for unsupported versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2).

Owner of this card:

Henning Koch
Last edit:
8 months 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 short-lived cookies to improve usability.
Accept or learn more