From 4fedf697274edd43b9a8e74ce0bf52c607cd5e3e Mon Sep 17 00:00:00 2001 From: Remi <73385395+itsrubberduck@users.noreply.github.com> Date: Sat, 18 Oct 2025 13:23:14 +0200 Subject: [PATCH] Load Hotjar after cookie consent --- plugins/hotjar.client.ts | 54 ++++++++++++++++++++++++++++++++++------ 1 file changed, 47 insertions(+), 7 deletions(-) diff --git a/plugins/hotjar.client.ts b/plugins/hotjar.client.ts index 3274d03..3c9d7dd 100644 --- a/plugins/hotjar.client.ts +++ b/plugins/hotjar.client.ts @@ -1,3 +1,7 @@ +import { defineNuxtPlugin } from '#app'; +import { watch } from 'vue'; +import { useCookieConsent } from '~/composables/useCookieConsent'; + declare global { interface Window { hj?: ((...args: unknown[]) => void) & { q?: unknown[][] }; @@ -42,18 +46,54 @@ const appendHotjarScript = () => { return true; }; +const removeHotjarScript = () => { + const script = document.getElementById(HOTJAR_SCRIPT_ID); + if (script && script.parentNode) { + script.parentNode.removeChild(script); + } +}; + +const disableHotjar = () => { + if (typeof window === 'undefined') { + return; + } + + window._hjOptOut = true; + removeHotjarScript(); + window.hj = undefined; + window._hjSettings = undefined; +}; + +const enableHotjar = () => { + if (typeof window === 'undefined') { + return false; + } + + window._hjOptOut = false; + ensureHotjarStub(); + return appendHotjarScript(); +}; + export default defineNuxtPlugin(() => { if (!import.meta.client) { return; } const hasLoaded = useState('hotjar-loaded', () => false); + const { analyticsEnabled } = useCookieConsent(); - if (!hasLoaded.value) { - ensureHotjarStub(); - - if (appendHotjarScript()) { - hasLoaded.value = true; - } - } + watch( + () => analyticsEnabled.value, + (enabled) => { + if (enabled) { + if (enableHotjar()) { + hasLoaded.value = true; + } + } else { + disableHotjar(); + hasLoaded.value = false; + } + }, + { immediate: true } + ); });