Skip to content

Commit

Permalink
fix: init all tags when granting consent
Browse files Browse the repository at this point in the history
  • Loading branch information
johannschopplich committed Feb 9, 2024
1 parent 49f9a3c commit acd0bb6
Show file tree
Hide file tree
Showing 4 changed files with 10 additions and 8 deletions.
Binary file removed .github/og.jpg
Binary file not shown.
Binary file added .github/social-card.jpg
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 2 additions & 2 deletions src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,10 @@ export interface ModuleOptions {
config?: Record<string, any>

/**
* Whether to initially consent to tracking if the tag ID is for Google Analytics.
* Whether to initialize the Google tag script immediately after the page has loaded.
*
* @remarks
* If set to `true`, the Google tag ID script will be loaded immediately.
* Set this to `false` to delay the initialization until you call the `grantConsent` function manually.
*
* @default true
*/
Expand Down
14 changes: 8 additions & 6 deletions src/runtime/composables/useGtag.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,34 +21,36 @@ export function useGtag() {
hasConsent = true,
}: UseGtagConsentOptions) => {
if (process.client) {
const tag = tags?.find(tag => tag.id === id) ?? (id ? { id } : tags[0])
const _tags = [...tags]
if (id && !_tags.find(tag => tag.id === id))
_tags.unshift({ id })

if (!tag) {
if (!_tags.length) {
console.error('[nuxt-gtag] Missing Google tag ID')
return
}

if (!hasConsent) {
disableGtag(tag.id)
disableGtag(_tags[0].id)
return
}

// Initialize `dataLayer` if the client plugin didn't initialize it
// (because no ID was provided in the module options).
if (!window.dataLayer)
initGtag({ tags: [tag] })
initGtag({ tags: _tags })

// If the `dataLayer` has more than two items
// it is considered to be initialized.
if (window.dataLayer!.length > 2) {
// Re-enable Google Analytics if it was disabled before.
enableGtag(tag.id)
enableGtag(_tags[0].id)
return
}

// Inject the Google tag script.
useHead({
script: [{ src: withQuery(options.url, { id: tag.id }) }],
script: [{ src: withQuery(options.url, { id: _tags[0].id }) }],
})
}
}
Expand Down

0 comments on commit acd0bb6

Please sign in to comment.