Presently, the JavaScript function grecaptcha.execute
is triggered on page load, as shown in the first example below. This means that the reCAPTCHA challenge occurs as soon as the page loads. A more ideal scenario would be to trigger it when the form submit button is clicked instead.
I attempted this by moving the execution into the submit event (as shown in the second JS example) and placing the axios function within a promise. However, it seems that the form is being submitted before the grecaptcha.execute completes its execution.
What am I missing here? This is my initial encounter with promises, so perhaps I don't quite understand how they operate? Is there a better solution for this issue? Or could it be something else entirely?
HTML
<head>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" defer></script>
</head>
JS
const form = document.querySelector('#subscribe');
let recaptchaToken;
const recaptchaExecute = (token) => {
recaptchaToken = token;
};
const onloadCallback = () => {
grecaptcha.render('recaptcha', {
'sitekey': 'abcexamplesitekey',
'callback': recaptchaExecute,
'size': 'invisible',
});
grecaptcha.execute();
};
form.addEventListener('submit', (e) => {
e.preventDefault();
const formResponse = document.querySelector('.js-form__error-message');
axios({
method: 'POST',
url: '/actions/newsletter/verifyRecaptcha',
data: qs.stringify({
recaptcha: recaptchaToken,
[window.csrfTokenName]: window.csrfTokenValue,
}),
config: {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
},
}).then((data) => {
if (data && data.data.success) {
formResponse.innerHTML = '';
form.submit();
} else {
formResponse.innerHTML = 'Form submission failed, please try again';
}
});
}
JS
const onloadCallback = () => {
grecaptcha.render('recaptcha', {
'sitekey': 'abcexamplesitekey',
'callback': recaptchaExecute,
'size': 'invisible',
});
};
form.addEventListener('submit', (e) => {
e.preventDefault();
const formResponse = document.querySelector('.js-form__error-message');
grecaptcha.execute().then(axios({
method: 'POST',
url: '/actions/newsletter/verifyRecaptcha',
data: qs.stringify({
recaptcha: recaptchaToken,
[window.csrfTokenName]: window.csrfTokenValue,
}),
config: {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
},
})).then((data) => {
if (data && data.data.success) {
formResponse.innerHTML = '';
form.submit();
} else {
formResponse.innerHTML = 'Form submission failed, please try again';
}
});
}