-
Notifications
You must be signed in to change notification settings - Fork 325
/
Copy pathcaptcha.ts
57 lines (49 loc) · 1.43 KB
/
captcha.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
import { loadScript } from '@clerk/shared';
interface RenderOptions {
sitekey: string;
retry: string;
callback: (token: string) => void;
'error-callback': (err: any) => void;
}
declare global {
export interface Window {
turnstile: { execute: (container?: string | HTMLElement | null, params?: RenderOptions) => void };
}
}
const WIDGET_CLASSNAME = 'clerk-captcha';
export async function loadCaptcha(url: string) {
if (!window.turnstile) {
await loadScript(url, { defer: true });
}
return window.turnstile;
}
export const getCaptchaToken = async (captchaOptions: { siteKey: string; scriptUrl: string }) => {
const { siteKey: sitekey, scriptUrl } = captchaOptions;
let captchaToken = '';
const div = document.createElement('div');
div.classList.add(WIDGET_CLASSNAME);
document.body.appendChild(div);
const captcha = await loadCaptcha(scriptUrl);
const handleCaptchaTokenGeneration = (): Promise<string> => {
return new Promise((resolve, reject) => {
return captcha.execute(`.${WIDGET_CLASSNAME}`, {
sitekey,
retry: 'never',
callback: function (token: string) {
resolve(token);
},
'error-callback': function (err) {
reject(err);
},
});
});
};
try {
captchaToken = await handleCaptchaTokenGeneration();
} catch (e) {
console.warn(e);
} finally {
document.body.removeChild(div);
}
return captchaToken;
};