Tracking Virtual PageViews in AMP with Google Analytics

When showing more than one article on a single AMP template, you might want to use the virtual page views feature to track that second page view as the secondary articles come into view.

This is a more advanced feature which the documentation does not cover.

At the moment only single amp elements are supported for being used as visibility triggers in amp-analytics, and that’s why the recommended way is to wrap your element inside an <amp-layout> tag. Since you need some more data to pass to the trigger event, including you can make use of the data-vars- attribute on that element like this:

<amp-layout class="virtual-pageview-1" data-vars-page-location="https://example.com/1" data-vars-page-title="Title 1"><div>your own elements</div></amp-layout>

And then, inside of the JSON configuration of analytics you would go along these lines:

{
"vars": {
"account": "UA-XXXXXXXX-X"
},
"triggers": {
"trackPageview": {
"on": "visible",
"request": "pageview"
},
"virtualPageview1": {
"selector": ".virtual-pageview-1",
"on": "visible",
"request": "pageview",
"vars": {
"documentLocation": "${pageLocation}",
"title": "${pageTitle}"
}
}
}
}

If you have several virtual pages you want to track the page views against, you’d have to duplicate this against several .virtual-pageview-X amp elements and update the analytics JSON configuration accordingly. Hopefully at some point collections will also be supported.

One gotcha is – these trigger selectors have to match otherwise they yield a console error. I had to find a less than ideal workaround for pages which did not have the virtual pageviews to track against. I’ve done that workaround by placing a hidden amp-layout element <amp class="virtual-pageview-1 hidden"></amp-layout>and I’ve added a basic .hidden { display: none; } css rule to avoid sending empty POST requests to analytics. If you stumbled upon a more elegant way to achieve this, please share it in the comments.

Comments