Fix Hotjar loading after cookie consent

This commit is contained in:
Remi
2025-09-18 13:36:27 +02:00
committed by itsrubberduck
parent 0521d28759
commit 88497a3848
2 changed files with 38 additions and 25 deletions

View File

@@ -9,7 +9,6 @@ export default defineNuxtConfig({
'nuxt-aos',
'@pinia/nuxt',
'nuxt-mongoose',
'nuxt-module-hotjar',
'@nuxt/image',
],
aos: {once: true, duration: 600, easing: 'ease-out'},

View File

@@ -1,3 +1,4 @@
import type { Ref } from 'vue';
import { watch } from 'vue';
declare global {
@@ -12,15 +13,11 @@ const HOTJAR_ID = 6522897;
const HOTJAR_VERSION = 6;
const HOTJAR_SCRIPT_ID = 'hotjar-tracking-script';
const injectHotjar = () => {
const ensureHotjarStub = () => {
if (typeof window === 'undefined') {
return;
}
if (window.hj && window._hjSettings?.hjid === HOTJAR_ID) {
return;
}
window.hj =
window.hj ||
function (...args: unknown[]) {
@@ -28,14 +25,16 @@ const injectHotjar = () => {
};
window._hjSettings = { hjid: HOTJAR_ID, hjsv: HOTJAR_VERSION };
};
const appendHotjarScript = () => {
if (document.getElementById(HOTJAR_SCRIPT_ID)) {
return;
return true;
}
const head = document.head || document.getElementsByTagName('head')[0];
if (!head) {
return;
return false;
}
const script = document.createElement('script');
@@ -43,6 +42,33 @@ const injectHotjar = () => {
script.async = true;
script.src = `https://static.hotjar.com/c/hotjar-${HOTJAR_ID}.js?sv=${HOTJAR_VERSION}`;
head.appendChild(script);
return true;
};
const enableHotjar = (hasLoaded: Ref<boolean>) => {
if (typeof window === 'undefined') {
return;
}
window._hjOptOut = false;
if (hasLoaded.value) {
return;
}
ensureHotjarStub();
if (appendHotjarScript()) {
hasLoaded.value = true;
}
};
const disableHotjar = () => {
if (typeof window === 'undefined') {
return;
}
window._hjOptOut = true;
};
export default defineNuxtPlugin(() => {
@@ -53,27 +79,15 @@ export default defineNuxtPlugin(() => {
const { analyticsEnabled } = useCookieConsent();
const hasLoaded = useState('hotjar-loaded', () => false);
const loadIfNecessary = () => {
if (!hasLoaded.value) {
injectHotjar();
hasLoaded.value = true;
window._hjOptOut = false;
}
};
if (analyticsEnabled.value) {
loadIfNecessary();
}
watch(
analyticsEnabled,
() => analyticsEnabled.value,
(allowed) => {
if (allowed) {
loadIfNecessary();
} else if (typeof window !== 'undefined') {
window._hjOptOut = true;
enableHotjar(hasLoaded);
} else {
disableHotjar();
}
},
{ immediate: false }
{ immediate: true }
);
});