Skip to content

Commit a3bef61

Browse files
committed
fix recaptcha completion & render
1 parent 1e17f02 commit a3bef61

1 file changed

Lines changed: 26 additions & 4 deletions

File tree

src/lib/components/Contact.svelte

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -58,14 +58,22 @@
5858
triggerToast('Please enter a valid email address', 'error');
5959
return;
6060
}
61+
window.grecaptcha = window.grecaptcha || {};
62+
63+
const recaptchaResponse = window.document.getElementById('recaptchaResponse').value;
64+
if (!recaptchaResponse) {
65+
triggerToast('Please complete the ReCAPTCHA', 'error');
66+
return;
67+
}
6168
const response = await fetch(formSpree, {
6269
method: 'POST',
6370
body: JSON.stringify({
6471
firstname,
6572
lastname,
6673
email,
6774
phone,
68-
message
75+
message,
76+
'g-recaptcha-response': recaptchaResponse
6977
}),
7078
headers: {
7179
Accept: 'application/json'
@@ -85,13 +93,22 @@
8593
}
8694
} catch (error) {
8795
triggerToast('Oops! There was a problem submitting your form', 'error');
96+
} finally {
97+
if (window.grecaptcha) {
98+
window.grecaptcha.reset();
99+
}
88100
}
89101
}
90102
</script>
91103

92104
<svelte:head>
93-
{#if env !== 'development'}
94-
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
105+
{#if recaptchaSiteKey && env !== 'development'}
106+
<script src="https://www.google.com/recaptcha/api.js"></script>
107+
<script>
108+
function recaptchaCallback(token) {
109+
window.document.getElementById('recaptchaResponse').value = token;
110+
}
111+
</script>
95112
{/if}
96113
</svelte:head>
97114
<section id={Section.Contact} class="px-3 py-5 rounded-none lg:py-10 lg:px-5 card bg-surface-400">
@@ -184,7 +201,12 @@
184201
/>
185202
</label>
186203
{#if recaptchaSiteKey && env !== 'development'}
187-
<div class="g-recaptcha" data-sitekey={recaptchaSiteKey}></div>
204+
<div
205+
class="g-recaptcha"
206+
data-sitekey={recaptchaSiteKey}
207+
data-callback="recaptchaCallback"
208+
></div>
209+
<input id="recaptchaResponse" name="recaptchaResponse" type="hidden" />
188210
{/if}
189211
<div class="mx-2 mt-2 mb-6 text-white bg-blue-500 rounded-xl md:justify-self-end btn">
190212
<button type="submit"> Send message </button>

0 commit comments

Comments
 (0)