mirror of
https://github.com/OpenSquawk/OpenSquawk
synced 2026-08-05 17:05:53 +08:00
Load Hotjar after cookie consent
This commit is contained in:
@@ -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 }
|
||||
);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user