nuxt / scripts

Third-Party Scripts Meets Nuxt Developer Experience.
https://scripts.nuxt.com
MIT License
318 stars 42 forks source link

How to use GTM with router support? #259

Closed hjelmdal closed 1 month ago

hjelmdal commented 1 month ago

📚 Is your documentation request related to a problem?

I tried following the Nuxt Scripts guide for implementing GTM - compared to other Nuxt / Vue packages, I don't have any options to hook into the router, for firing events on route changes out of the box - Am I missing something here, or how do I make GTM pickup route changes out of the box?

🔍 Where should you find it?

https://scripts.nuxt.com/scripts/tracking/google-tag-manager

ℹī¸ Additional context

I tried using the Tag assistant to verify the firing of the Tag, and can confirm that it is only recording events on hard refresh.

harlan-zw commented 1 month ago

Hi, thank you for the question.

I've pushed up these changes to the docs, can you let me know if it's not clear or if you have any further questions.

Guide: Sending Page Events

If you'd like to manually send page events to Google Tag Manager, you can use the proxy with the useScriptEventPage composable. This composable will trigger the provided function on route change after the page title has been updated.

const { proxy } = useScriptGoogleTagManager({
  id: 'YOUR_ID' // id is only needed if you haven't configured globally
}) 

useScriptEventPage((title, path) => {
  // triggered on route change after title is updated
  proxy.dataLayer.push({ 
    event: 'pageview',
    title, 
    path 
  })
})
hjelmdal commented 1 month ago

Hi,

Thanks for your reply.. Forgive me for being no expert, but can you elaborate or make it very clear where to put that code, for people that wants to add standard page tracking done automatically on every route change (and not just on title change, if I understand you correct?), so that the implementation is clear and almost out of the box, but with the power of Nuxt Scripts ?

Thanks a million 🙏

harlan-zw commented 1 month ago

Hey, sure. This would go in your app.vue, a layout file, or a plugin. It depends on your personal preference. I'd usually just throw it into app.vue.

I'll update docs so that's clearer.