Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

How to trigger a page view event in Google Analytics on a Single Page Application?

According to this on Single Page Applications you load the google tag script when the user first loads the app, then on subsequent page views you programmatically update the page path like so:

gtag('config', 'UA-1234567-89', {'page_path': '/about-us'});

My question is, when you call this code does it automatically send a new page view too?

So for example let's say my SPA has a root URL of:

https://helloworld.com

And the user clicks on the /about-us link from the homepage. Does this mean there will be 2 page view events?

  • First https://helloworld.com/
  • Then https://helloworld.com/about-us

Or do I need to do something else after updating the page path to send the page view event to GA for the about us page?

gtag('config', 'UA-1234567-89', {'page_path': '/about-us'});

// Call something else here to trigger new page view using updated path here?
question from:https://stackoverflow.com/questions/66067424/how-to-trigger-a-page-view-event-in-google-analytics-on-a-single-page-applicatio

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you're using gtag.js then your code snippet for implementation will look something like this:

<script async src="https://www.googletagmanager.com/gtag/js?id=UA-00000000-1"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());


  gtag('config', 'UA-00000000-1'); //modify this line
</script>

To prevent it from sending a pageview on load you just make the adjustment like so:

gtag('config', 'GA_MEASUREMENT_ID', {'send_page_view': false}); //replace the id with your own id

For SPAs, I'd recommend Google Tag Manager instead and use datalayer events or the included history change trigger for tracking, there might be a slight learning curve to start, but I think it'll simplify your code and make it more "portable" should you switch analytics platforms later on.

More info on GTM: https://developers.google.com/tag-manager/devguide


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...