I'm in a bind, and Javascript world it's very weird.
I need to make a form with the reCAPTCHA v3 token resolved before proceeding with form submission. Since some events are bound to the form submit
event, the event loop must wait until it's resolved otherwise it fails:
- Some forms have validation events that prevent the submission if there are errors (like an invalid value inside an input).
- If the user clicks the form too quickly (thanks to the autocomplete) when the page loads, and the token is still not retrieved, the request returns an error.
While I'm trying to do is to have a listener for the submit
event that blocks the submission until the token is resolved before going on with other listeners.
Currently the documentation on the reCAPTCHA script is zero, and I haven't found a reliable way to actually and forcefully resolve the token. The reCAPTCHA script is asynchronous, so there is no way to wait until the token is resolved:
// Let's retrieve the form by its id.
let form = document.getElementById('example_form');
let addToken = (form) => {
grecaptcha.execute('site_key', {
// some options
}).then(token => {
// Include the token as an input inside the form so it's sent.
});
};
form.addEventListener('submit', () => {
return addToken(form); // <-- This won't work, since it's async.
});