Skip to content

Commit b83dbe7

Browse files
committed
Forbedrer fjerning av script og sjekk av samtykke for ux signals
1 parent 9d498ee commit b83dbe7

File tree

1 file changed

+15
-14
lines changed

1 file changed

+15
-14
lines changed

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

+15-14
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import React, { useEffect } from 'react';
2-
import { EditorHelp } from 'components/_editor-only/editor-help/EditorHelp';
32
import { getCurrentConsent } from '@navikt/nav-dekoratoren-moduler';
3+
import { EditorHelp } from 'components/_editor-only/editor-help/EditorHelp';
44

55
import style from './UxSignalsWidget.module.scss';
66

@@ -17,52 +17,53 @@ type Consent = {
1717
};
1818

1919
const uxSignalsScriptUrl = 'https://widget.uxsignals.com/embed.js';
20+
let scriptAddTimeout: ReturnType<typeof setTimeout>;
2021

2122
export const UxSignalsWidget = ({ embedCode }: UxSignalsWidgetProps) => {
2223
// If the cookie banner is visible, the user has not taken any action yet.
2324
// Wait and see if the user takes action before adding the script if consent is given..
24-
const checkConsentOrWait = ({ consent, userActionTaken }: Consent) => {
25+
const checkConsentOrWait = (tries: number = 0) => {
26+
const { consent, userActionTaken }: Consent = getCurrentConsent();
2527
if (consent.surveys && consent.analytics) {
2628
addUXSignalsScript();
2729
return;
2830
}
29-
if (!userActionTaken) {
30-
setTimeout(() => {
31-
console.log('waiting...');
32-
checkConsentOrWait(getCurrentConsent());
33-
}, 1000);
31+
// Wait max 20 seconds for user respond to the cookie banner
32+
// (userActionTaken) or give up.
33+
if (!userActionTaken && tries < 20) {
34+
scriptAddTimeout = setTimeout(() => {
35+
checkConsentOrWait(tries + 1);
36+
}, 3000);
3437
}
35-
36-
console.log('no consent or user action taken');
3738
};
3839

3940
const addUXSignalsScript = () => {
4041
if (document.querySelector(`script[src="${uxSignalsScriptUrl}"]`)) {
4142
return;
4243
}
4344

44-
console.log('adding script');
45-
4645
const script = document.createElement('script');
4746
script.src = uxSignalsScriptUrl;
4847
script.async = true;
4948
document.body.appendChild(script);
5049
};
5150

5251
const removeUXSignalsScript = () => {
53-
console.log('removing script');
5452
const script = document.querySelector(`script[src="${uxSignalsScriptUrl}"]`);
5553
if (script) {
5654
document.body.removeChild(script);
5755
}
5856
};
5957

6058
useEffect(() => {
61-
const consent = getCurrentConsent();
62-
checkConsentOrWait(consent);
59+
checkConsentOrWait();
6360
return () => {
61+
if (scriptAddTimeout) {
62+
clearTimeout(scriptAddTimeout);
63+
}
6464
removeUXSignalsScript();
6565
};
66+
/* eslint-disable-next-line react-hooks/exhaustive-deps */
6667
}, []);
6768

6869
return (

0 commit comments

Comments
 (0)