I have a basic HTMX form, that I want to integrate with Google reCaptcha (v3) so that when the user clicks the submit button, some JavaScript will call the reCaptcha API to obtain a token, which is then added to a hidden field which the back end can pick-up.
Here is my form:
<form id="form" hx-post="/page" hx-target="#content">
<input id="recaptcha-token" type="hidden" name="ReCaptchaToken" />
<button type="submit">Submit</button>
</form>
Initially I was thinking of hooking into the htmx:configRequest event to modify the parameters sent in the request like so:
<script>
document.body.addEventListener('htmx:configRequest', (e) => {
grecaptcha.ready(function() {
grecaptcha.execute('reCAPTCHA_site_key', {action: 'submit'}).then(function(token) {
e.detail.parameters.ReCaptchaToken = token;
});
});
});
</script>
But of course this doesn't work because of async nature of execute - i.e. the event handler finishes before resolving the execute promise.
How can I integrate the reCaptcha call before the HTMX form post?