forked from opencollective/opencollective-frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrecaptcha.js
47 lines (37 loc) · 1.27 KB
/
recaptcha.js
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
import { getEnvVar } from './env-utils';
import { loadScriptAsync } from './utils';
const getRecaptchaSiteKey = () => getEnvVar('RECAPTCHA_SITE_KEY');
const getRecaptchaScriptUrl = () => {
const apiKey = getRecaptchaSiteKey();
if (!apiKey) {
throw new Error("'RECAPTCHA_SITE_KEY' is undefined.");
}
return `https://www.google.com/recaptcha/api.js?render=${apiKey}`;
};
const RECAPTCHA_SCRIPT_ID = 'recaptcha';
const loadRecaptcha = async () => {
if (typeof window === 'undefined') {
return;
}
if (typeof window.grecaptcha !== 'undefined') {
return;
}
return loadScriptAsync(getRecaptchaScriptUrl(), { attrs: { id: RECAPTCHA_SCRIPT_ID } });
};
const getRecaptcha = async () => {
await loadRecaptcha();
return window.grecaptcha;
};
const unloadRecaptcha = () => {
if (typeof window === 'undefined') {
return;
}
// Remove scripts
document.getElementById(RECAPTCHA_SCRIPT_ID)?.remove();
document.querySelectorAll('script[src^="https://www.gstatic.com/recaptcha"]').forEach(e => e.remove());
// Remove widget
document.querySelectorAll('.grecaptcha-badge').forEach(e => e.remove());
// Remove global instance
delete window.grecaptcha;
};
export { getRecaptchaScriptUrl, loadRecaptcha, getRecaptcha, getRecaptchaSiteKey, unloadRecaptcha };