Skip to content

Commit

Permalink
fix: send initial page view manually (closes #11)
Browse files Browse the repository at this point in the history
  • Loading branch information
johannschopplich committed Apr 18, 2023
1 parent 7462975 commit da5692d
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
10 changes: 9 additions & 1 deletion src/runtime/composables/useGtagConsent.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useHead, useRuntimeConfig } from '#imports'
import { gtag } from '../gtag'
import { useHead, useRoute, useRuntimeConfig } from '#imports'

export function useGtagConsent(hasConsent: boolean) {
const { gtag: { id } } = useRuntimeConfig().public
Expand All @@ -16,6 +17,13 @@ export function useGtagConsent(hasConsent: boolean) {
useHead({
script: [{ src: `https://www.googletagmanager.com/gtag/js?id=${id}` }],
})

// Send initial `page_view` event
gtag('event', 'page_view', {
page_location: window.location.href,
page_path: useRoute().path,
page_title: document.title,
})
}
else {
// Re-enable Google Analytics
Expand Down
9 changes: 8 additions & 1 deletion src/runtime/plugin.client.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { gtag } from './gtag'
import { defineNuxtPlugin, useHead, useRuntimeConfig } from '#imports'
import { defineNuxtPlugin, useHead, useRoute, useRuntimeConfig } from '#imports'

export default defineNuxtPlugin(() => {
const {
Expand Down Expand Up @@ -29,4 +29,11 @@ export default defineNuxtPlugin(() => {
},
],
})

// Send initial `page_view` event
gtag('event', 'page_view', {
page_location: window.location.href,
page_path: useRoute().path,
page_title: document.title,
})
})

0 comments on commit da5692d

Please # to comment.