Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions docs/content/scripts/tracking/google-tag-manager.md
Original file line number Diff line number Diff line change
Expand Up @@ -198,3 +198,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
})
})
```
8 changes: 5 additions & 3 deletions src/runtime/registry/google-tag-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,12 +159,14 @@ export function useScriptGoogleTagManager<T extends GoogleTagManagerApi>(
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
Expand Down
Loading