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 } + ); });