diff --git a/docs/content/scripts/tracking/google-tag-manager.md b/docs/content/scripts/tracking/google-tag-manager.md index 0afcadef..5aa25220 100644 --- a/docs/content/scripts/tracking/google-tag-manager.md +++ b/docs/content/scripts/tracking/google-tag-manager.md @@ -232,3 +232,37 @@ function sendConversion() { `useScriptGoogleTagManager` initialize Google Tag Manager by itself. This means it pushes the `js`, `config` and the `gtm.start` events for you. If you need to configure GTM before it starts. For example, [setting the consent mode](https://developers.google.com/tag-platform/security/guides/consent?consentmode=basic). You can use the `onBeforeGtmStart` hook which is run right before we push the `gtm.start` event into the dataLayer. + +```vue +const { proxy } = useScriptGoogleTagManager({ + onBeforeGtmStart: (gtag) => { + // set default consent state to denied + gtag('consent', 'default', { + 'ad_user_data': 'denied', + 'ad_personalization': 'denied', + 'ad_storage': 'denied', + 'analytics_storage': 'denied', + 'wait_for_update': 500, + }) + + // if consent was already given, update gtag accordingly + if (consent.value === 'granted') { + gtag('consent', 'update', { + ad_user_data: consent.value, + ad_personalization: consent.value, + ad_storage: consent.value, + analytics_storage: consent.value + }) + } + } +}) + +// push pageview events to dataLayer +useScriptEventPage(({ title, path }) => { + proxy.dataLayer.push({ + event: 'pageview', + title, + path + }) +}) +``` diff --git a/src/runtime/registry/google-tag-manager.ts b/src/runtime/registry/google-tag-manager.ts index 96ab5506..23fc2905 100644 --- a/src/runtime/registry/google-tag-manager.ts +++ b/src/runtime/registry/google-tag-manager.ts @@ -159,12 +159,14 @@ export function useScriptGoogleTagManager( clientInit: import.meta.server ? undefined : () => { - // Initialize dataLayer if it doesn't exist + // Initialize dataLayer if it doesn't exist (window as any)[dataLayerName] = (window as any)[dataLayerName] || [] // Create gtag function - function gtag(...args: any[]) { - (window as any)[dataLayerName].push(args) + function gtag() { + // Pushing arguments to dataLayer is necessary for GTM to process events + // eslint-disable-next-line prefer-rest-params + (window as any)[dataLayerName].push(arguments) } // Allow custom initialization