Skip to content

Commit 1edcd3d

Browse files
endorfinharlan-zw
andauthored
fix(gtm): broken onBeforeGtmStart arguments (#494)
Co-authored-by: Harlan Wilton <harlan@harlanzw.com>
1 parent abe57c4 commit 1edcd3d

File tree

2 files changed

+39
-3
lines changed

2 files changed

+39
-3
lines changed

docs/content/scripts/tracking/google-tag-manager.md

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -232,3 +232,37 @@ function sendConversion() {
232232
`useScriptGoogleTagManager` initialize Google Tag Manager by itself. This means it pushes the `js`, `config` and the `gtm.start` events for you.
233233

234234
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.
235+
236+
```vue
237+
const { proxy } = useScriptGoogleTagManager({
238+
onBeforeGtmStart: (gtag) => {
239+
// set default consent state to denied
240+
gtag('consent', 'default', {
241+
'ad_user_data': 'denied',
242+
'ad_personalization': 'denied',
243+
'ad_storage': 'denied',
244+
'analytics_storage': 'denied',
245+
'wait_for_update': 500,
246+
})
247+
248+
// if consent was already given, update gtag accordingly
249+
if (consent.value === 'granted') {
250+
gtag('consent', 'update', {
251+
ad_user_data: consent.value,
252+
ad_personalization: consent.value,
253+
ad_storage: consent.value,
254+
analytics_storage: consent.value
255+
})
256+
}
257+
}
258+
})
259+
260+
// push pageview events to dataLayer
261+
useScriptEventPage(({ title, path }) => {
262+
proxy.dataLayer.push({
263+
event: 'pageview',
264+
title,
265+
path
266+
})
267+
})
268+
```

src/runtime/registry/google-tag-manager.ts

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -159,12 +159,14 @@ export function useScriptGoogleTagManager<T extends GoogleTagManagerApi>(
159159
clientInit: import.meta.server
160160
? undefined
161161
: () => {
162-
// Initialize dataLayer if it doesn't exist
162+
// Initialize dataLayer if it doesn't exist
163163
(window as any)[dataLayerName] = (window as any)[dataLayerName] || []
164164

165165
// Create gtag function
166-
function gtag(...args: any[]) {
167-
(window as any)[dataLayerName].push(args)
166+
function gtag() {
167+
// Pushing arguments to dataLayer is necessary for GTM to process events
168+
// eslint-disable-next-line prefer-rest-params
169+
(window as any)[dataLayerName].push(arguments)
168170
}
169171

170172
// Allow custom initialization

0 commit comments

Comments
 (0)