-
Notifications
You must be signed in to change notification settings - Fork 8
/
utils.ts
61 lines (49 loc) · 1.91 KB
/
utils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
type HotjarCommand = 'event' | 'identify' | 'stateChange';
export type InitOpts = {
debug?: boolean,
nonce?: string,
};
export interface WindowWithHotjar extends Window {
hj?: (method: HotjarCommand, ...data: unknown[]) => void;
}
declare const window: WindowWithHotjar;
const hasWindow = () => typeof window !== 'undefined';
export const checkReadyState = (): boolean => {
if (hasWindow() && window.hj) {
return true;
}
return false;
};
export const executeHotjarCommand = (command: HotjarCommand, ...args: unknown[]): void => {
if (hasWindow() && window.hj) {
return window.hj(command, ...args);
}
throw Error('Hotjar is not available, make sure init has been called.');
};
const appendScript = (scriptText: string, scriptId: string, nonce: undefined | string = undefined): boolean => {
try {
const existingScript = document.getElementById(scriptId) as HTMLScriptElement;
const script = existingScript || document.createElement('script');
script.id = scriptId;
script.nonce = nonce;
script.innerText = scriptText;
script.crossOrigin = 'anonymous';
document.head.appendChild(script);
return true;
} catch {
return false;
}
};
export const initScript = (
hotjarId: number,
hotjarVersion: number,
opts?: InitOpts
): void => {
const isDebug = opts?.debug || false;
const hotjarScriptCode = `(function(h,o,t,j,a,r){h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)};h._hjSettings={hjid:${hotjarId},hjsv:${hotjarVersion},hjdebug:${isDebug}};a=o.getElementsByTagName('head')[0];r=o.createElement('script');r.async=1;r.src=t+h._hjSettings.hjid+j+h._hjSettings.hjsv;a.appendChild(r);})(window,document,'https://static.hotjar.com/c/hotjar-','.js?sv=');`;
const isAppended = appendScript(hotjarScriptCode, 'hotjar-init-script', opts?.nonce);
if (isAppended && checkReadyState()) {
return;
}
throw Error('Failed to initialize Hotjar tracking script.');
};