Read more

Using Google Analytics with Unpoly

Henning Koch
July 19, 2016Software engineer at makandra GmbH

Use the official Unpoly documentation instead: Tracking page views

The default Google Analytics might not work as expected with your Unpoly Show archive.org snapshot 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.

Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

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

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>
Posted by Henning Koch to makandra dev (2016-07-19 18:23)