1
1
import React , { useEffect } from 'react' ;
2
- import { EditorHelp } from 'components/_editor-only/editor-help/EditorHelp' ;
3
2
import { getCurrentConsent } from '@navikt/nav-dekoratoren-moduler' ;
3
+ import { EditorHelp } from 'components/_editor-only/editor-help/EditorHelp' ;
4
4
5
5
import style from './UxSignalsWidget.module.scss' ;
6
6
@@ -17,52 +17,53 @@ type Consent = {
17
17
} ;
18
18
19
19
const uxSignalsScriptUrl = 'https://widget.uxsignals.com/embed.js' ;
20
+ let scriptAddTimeout : ReturnType < typeof setTimeout > ;
20
21
21
22
export const UxSignalsWidget = ( { embedCode } : UxSignalsWidgetProps ) => {
22
23
// If the cookie banner is visible, the user has not taken any action yet.
23
24
// 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 ( ) ;
25
27
if ( consent . surveys && consent . analytics ) {
26
28
addUXSignalsScript ( ) ;
27
29
return ;
28
30
}
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 ) ;
34
37
}
35
-
36
- console . log ( 'no consent or user action taken' ) ;
37
38
} ;
38
39
39
40
const addUXSignalsScript = ( ) => {
40
41
if ( document . querySelector ( `script[src="${ uxSignalsScriptUrl } "]` ) ) {
41
42
return ;
42
43
}
43
44
44
- console . log ( 'adding script' ) ;
45
-
46
45
const script = document . createElement ( 'script' ) ;
47
46
script . src = uxSignalsScriptUrl ;
48
47
script . async = true ;
49
48
document . body . appendChild ( script ) ;
50
49
} ;
51
50
52
51
const removeUXSignalsScript = ( ) => {
53
- console . log ( 'removing script' ) ;
54
52
const script = document . querySelector ( `script[src="${ uxSignalsScriptUrl } "]` ) ;
55
53
if ( script ) {
56
54
document . body . removeChild ( script ) ;
57
55
}
58
56
} ;
59
57
60
58
useEffect ( ( ) => {
61
- const consent = getCurrentConsent ( ) ;
62
- checkConsentOrWait ( consent ) ;
59
+ checkConsentOrWait ( ) ;
63
60
return ( ) => {
61
+ if ( scriptAddTimeout ) {
62
+ clearTimeout ( scriptAddTimeout ) ;
63
+ }
64
64
removeUXSignalsScript ( ) ;
65
65
} ;
66
+ /* eslint-disable-next-line react-hooks/exhaustive-deps */
66
67
} , [ ] ) ;
67
68
68
69
return (
0 commit comments