-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgoogleRecaptcha.ts
More file actions
58 lines (49 loc) · 1.51 KB
/
googleRecaptcha.ts
File metadata and controls
58 lines (49 loc) · 1.51 KB
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
declare global {
interface Window {
grecaptcha: any;
}
var grecaptcha: any;
}
const DEFAULT_SITE_KEY = "6LeXSIIqAAAAAJlp04ct42518YoNJeWiUtUTItTb";
const widgetIds : {[siteKey: string]: number} = {};
export async function getRecaptchaToken(sitekey?: string, action?: string){
// Wait for script tag to load
if (!window.grecaptcha){
for (let i = 0; i<10; i++){
await new Promise((resolve) => setTimeout(resolve, 500));
if (window.grecaptcha)
break;
}
}
return new Promise((resolve, reject) => {
if (!sitekey)
sitekey = DEFAULT_SITE_KEY;
grecaptcha.ready(function() {
const elemId = `recaptcha-${sitekey}`;
let widgetId;
if (widgetIds[sitekey] === undefined){
const elem = document.createElement("div");
elem.id = elemId;
document.body.getElementsByTagName("app-root")[0].append(elem);
widgetId = grecaptcha.render(elemId, {
sitekey,
size: 'invisible'
});
widgetIds[sitekey] = widgetId;
} else {
widgetId = widgetIds[sitekey];
const elem = document.getElementById(elemId).getElementsByClassName("grecaptcha-badge")[0] as HTMLDivElement;
if (elem) elem.style.visibility = "visible";
}
grecaptcha.execute(widgetId, {action: action ?? "recaptcha"}).then(function(token) {
resolve(token);
setTimeout(() => {
const elem = document.getElementById(elemId).getElementsByClassName("grecaptcha-badge")[0] as HTMLDivElement;
if (elem) elem.style.visibility = "hidden";
}, 5000);
}).catch(e => {
reject(e);
});
});
})
}