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.
Luckily you can fix this.
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');
});
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>