|
1 | 1 | import React, { useEffect } from 'react';
|
| 2 | +import { getCurrentConsent } from '@navikt/nav-dekoratoren-moduler'; |
2 | 3 | import { EditorHelp } from 'components/_editor-only/editor-help/EditorHelp';
|
3 | 4 |
|
4 | 5 | import style from './UxSignalsWidget.module.scss';
|
5 | 6 |
|
6 |
| -type Props = { |
| 7 | +type UxSignalsWidgetProps = { |
7 | 8 | embedCode: string;
|
8 | 9 | };
|
9 | 10 |
|
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 | + |
12 | 45 | const script = document.createElement('script');
|
13 |
| - script.src = 'https://widget.uxsignals.com/embed.js'; |
| 46 | + script.src = uxSignalsScriptUrl; |
14 | 47 | script.async = true;
|
15 | 48 | document.body.appendChild(script);
|
16 |
| - return () => { |
| 49 | + }; |
| 50 | + |
| 51 | + const removeUXSignalsScript = () => { |
| 52 | + const script = document.querySelector(`script[src="${uxSignalsScriptUrl}"]`); |
| 53 | + if (script) { |
17 | 54 | document.body.removeChild(script);
|
| 55 | + } |
| 56 | + }; |
| 57 | + |
| 58 | + useEffect(() => { |
| 59 | + checkConsentOrWait(); |
| 60 | + return () => { |
| 61 | + if (scriptAddTimeout) { |
| 62 | + clearTimeout(scriptAddTimeout); |
| 63 | + } |
| 64 | + removeUXSignalsScript(); |
18 | 65 | };
|
19 |
| - }); |
| 66 | + /* eslint-disable-next-line react-hooks/exhaustive-deps */ |
| 67 | + }, []); |
20 | 68 |
|
21 | 69 | return (
|
22 | 70 | <>
|
|
0 commit comments