Use gtag.js to track virtual pageviews

2019-08-29 05:56发布

问题:

I have a multipage registration form and I want to track user's path through the form using Google Tag Manager. My page uses a recommended code snippet in the header to track page view:

window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-XXXXXXXX');

According to documentation I generate a virtual page view when a user clicks a certain button in the form:

gtag('js', new Date());
gtag('config', 'UA-XXXXX', {
     'page_title' : 'User registration',
     'page_path': '/registration/page2'
});

However, this code doesn't add a new page view. It overrides the original one. What am I doing wrong? I want a new pageview to be generated when the user clicks a button.

回答1:

It doesn't look like you're using GTM, but gtag.js instead.

You'll need to trigger it on click events. Something like:

<button onclick="formStep2()">Click me</button>

Then for the formStep2() function:

function formStep2(){
    gtag('config', 'UA-XXXXX', {
     'page_title' : 'User registration',
     'page_path': '/registration/page2'
    });
}

Of course, you can setup the function to be more generic/useful by passing in a parameter indicating the path/title as well.