Skip to content

Commit 17c958b

Browse files
Merge pull request #2221 from navikt/disable-ux-signals
Disable ux signals når samtykke ikke er gitt
2 parents 96ac1ec + d589725 commit 17c958b

File tree

1 file changed

+54
-6
lines changed

1 file changed

+54
-6
lines changed

packages/nextjs/src/components/_common/uxsignalsWidget/UxSignalsWidget.tsx

+54-6
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,70 @@
11
import React, { useEffect } from 'react';
2+
import { getCurrentConsent } from '@navikt/nav-dekoratoren-moduler';
23
import { EditorHelp } from 'components/_editor-only/editor-help/EditorHelp';
34

45
import style from './UxSignalsWidget.module.scss';
56

6-
type Props = {
7+
type UxSignalsWidgetProps = {
78
embedCode: string;
89
};
910

10-
export const UxSignalsWidget = ({ embedCode }: Props) => {
11-
useEffect(() => {
11+
type Consent = {
12+
consent: {
13+
analytics: boolean;
14+
surveys: boolean;
15+
};
16+
userActionTaken: boolean;
17+
};
18+
19+
const uxSignalsScriptUrl = 'https://widget.uxsignals.com/embed.js';
20+
let scriptAddTimeout: ReturnType<typeof setTimeout>;
21+
22+
export const UxSignalsWidget = ({ embedCode }: UxSignalsWidgetProps) => {
23+
// If the cookie banner is visible, the user has not taken any action yet.
24+
// Wait and see if the user takes action before adding the script if consent is given..
25+
const checkConsentOrWait = (tries: number = 0) => {
26+
const { consent, userActionTaken }: Consent = getCurrentConsent();
27+
if (consent.surveys && consent.analytics) {
28+
addUXSignalsScript();
29+
return;
30+
}
31+
// Wait max 60 seconds for user respond to the cookie banner
32+
// (userActionTaken) or give up.
33+
if (!userActionTaken && tries < 60) {
34+
scriptAddTimeout = setTimeout(() => {
35+
checkConsentOrWait(tries + 1);
36+
}, 1000);
37+
}
38+
};
39+
40+
const addUXSignalsScript = () => {
41+
if (document.querySelector(`script[src="${uxSignalsScriptUrl}"]`)) {
42+
return;
43+
}
44+
1245
const script = document.createElement('script');
13-
script.src = 'https://widget.uxsignals.com/embed.js';
46+
script.src = uxSignalsScriptUrl;
1447
script.async = true;
1548
document.body.appendChild(script);
16-
return () => {
49+
};
50+
51+
const removeUXSignalsScript = () => {
52+
const script = document.querySelector(`script[src="${uxSignalsScriptUrl}"]`);
53+
if (script) {
1754
document.body.removeChild(script);
55+
}
56+
};
57+
58+
useEffect(() => {
59+
checkConsentOrWait();
60+
return () => {
61+
if (scriptAddTimeout) {
62+
clearTimeout(scriptAddTimeout);
63+
}
64+
removeUXSignalsScript();
1865
};
19-
});
66+
/* eslint-disable-next-line react-hooks/exhaustive-deps */
67+
}, []);
2068

2169
return (
2270
<>

0 commit comments

Comments
 (0)