#google analytics partytown

1 messages · Page 1 of 1 (latest)

deep violet
#

how do get gtag function to run on every page load when using view transitions?

still echoBOT
#

Hi @deep violet. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

To run the gtag function on every page load when using View Transitions in Astro, you can use the astro:page-load event. This event fires at the end of page navigation, after the new page is visible to the user and blocking styles and scripts are loaded. You can listen to this event on the document.

Here's an example of how you can use this event to run the gtag function on every page navigation:

<script>
document.addEventListener('astro:page-load', () => {
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', 'G-XXXXXXXXXX');
});
</script>

Please replace 'G-XXXXXXXXXX' with your actual Google Analytics ID.

Remember to include the Google Analytics script with the type="text/partytown" attribute as per the Astro Partytown integration guide:

<script type="text/partytown" async src="<https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>>

Again, replace 'G-XXXXXXXXXX' with your actual Google Analytics ID.

Sources:


Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: