Skip to content

Commit 1f3c1ab

Browse files
committed
Harden reCAPTCHA loading
1 parent 2d07dc1 commit 1f3c1ab

1 file changed

Lines changed: 29 additions & 5 deletions

File tree

src/pages/Contact.jsx

Lines changed: 29 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,19 +18,43 @@ export default function Contact() {
1818
document.body.appendChild(script);
1919
}, []);
2020

21-
const runRecaptcha = () =>
21+
const waitForRecaptcha = () =>
2222
new Promise((resolve) => {
23-
if (!RECAPTCHA_SITE_KEY || !window.grecaptcha?.enterprise) {
24-
resolve('');
23+
if (!RECAPTCHA_SITE_KEY) {
24+
resolve(null);
2525
return;
2626
}
27-
window.grecaptcha.enterprise.ready(() => {
28-
window.grecaptcha.enterprise
27+
28+
const poll = (attempts = 0) => {
29+
if (window.grecaptcha?.enterprise?.ready) {
30+
resolve(window.grecaptcha.enterprise);
31+
return;
32+
}
33+
34+
if (attempts > 50) {
35+
resolve(null);
36+
return;
37+
}
38+
39+
setTimeout(() => poll(attempts + 1), 100);
40+
};
41+
42+
poll();
43+
});
44+
45+
const runRecaptcha = async () => {
46+
const enterprise = await waitForRecaptcha();
47+
if (!enterprise) return '';
48+
49+
return new Promise((resolve) => {
50+
enterprise.ready(() => {
51+
enterprise
2952
.execute(RECAPTCHA_SITE_KEY, { action: 'contact' })
3053
.then(resolve)
3154
.catch(() => resolve(''));
3255
});
3356
});
57+
};
3458

3559
async function handleSubmit(event) {
3660
event.preventDefault();

0 commit comments

Comments
 (0)