From da5692da861e11d78080a106a037db51d31dedd7 Mon Sep 17 00:00:00 2001 From: Johann Schopplich Date: Tue, 18 Apr 2023 08:09:09 +0200 Subject: [PATCH] fix: send initial page view manually (closes #11) --- src/runtime/composables/useGtagConsent.ts | 10 +++++++++- src/runtime/plugin.client.ts | 9 ++++++++- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/src/runtime/composables/useGtagConsent.ts b/src/runtime/composables/useGtagConsent.ts index b22aa16..d69b224 100644 --- a/src/runtime/composables/useGtagConsent.ts +++ b/src/runtime/composables/useGtagConsent.ts @@ -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 @@ -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 diff --git a/src/runtime/plugin.client.ts b/src/runtime/plugin.client.ts index b87f238..ad04ef2 100644 --- a/src/runtime/plugin.client.ts +++ b/src/runtime/plugin.client.ts @@ -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 { @@ -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, + }) })