I'm developing a static website using SvelteKit to get my first approach to svelte. I got almost everything working as intended. Everything but the recaptcha protection on contact form.
I can obtain recaptcha token but I'm losing it the passing it to formData request. My relative code is:
<script lang="ts">
import * as yup from "yup";
import {createForm, ErrorMessage} from "svelte-forms-lib";
...
function getCaptcha(){
grecaptcha.ready(function () {
grecaptcha.execute('recaptcha-key', { action: 'contactForm' })
.then(function (token) {
console.log(token) // here I get the token
return token;
});
});
}
const sendMail= (values)=>
{
const url = '/sendmail.php';
const formData = new FormData();
let token = getCaptcha();
console.log('token: '+token); // here token is null
formData.append("token", token);
fetch(url, {
method: 'post',
body: formData,
})
.then(function (response) {
console.debug(response.status)
})
.catch(function (e) {
sendError = true;
console.debug(e);
});
}
</script>
Form submission is working fine except, obviously, for recaptcha token.
Thanks for any idea on how to solve it.