Skip to main content

I have created a custom Knockout.js binding to integrate Google reCAPTCHA into my MVC application using TypeScript. However, I'm encountering an issue where the token returned by grecaptcha.execute is null when the form is submitted. Below is the code for my custom binding handler:

 

import ko from 'knockout';


ko.bindingHandlers.recaptcha = {

init: function (element, valueAccessor) {

var params = ko.unwrap(valueAccessor());

var loadRecaptchaScript = function () {
if (!document.querySelector(`script[src="https://www.google.com/recaptcha/api.js?render=${params.siteKey}"]`)) {
var script = document.createElement('script');
script.src=`https://www.google.com/recaptcha/api.js?render=${params.siteKey}`;
script.defer = true;
script.async = true;
script.onload = function () {
initRecaptcha();
};
document.head.appendChild(script);
} else {
initRecaptcha();
}
};

var initRecaptcha = function () {
element.addEventListener('click', function (event: any) {
event.preventDefault();
generateRecaptchaToken(params.siteKey, params.action)
.then(function (token) {
if (token) {
params.tokenField.value = token;
element.form.submit();
} else {
console.error('Error generating reCAPTCHA token');
}
})
.catch(function (error) {
console.error('Error generating reCAPTCHA token:', error);
});
});
};
loadRecaptchaScript();
}
};
function generateRecaptchaToken(siteKey: string, action: string) {
return new Promise(function (resolve, reject) {
// Wait for the reCAPTCHA API to be ready
grecaptcha.ready(function () {
(async function () {
try {
grecaptcha.execute(siteKey, { action: action })
.then(function (token) {
resolve(token);
})
} catch (error) {
reject(error);
}
})();
});
});
}

Details:


I am using Knockout.js to create a custom binding for Google reCAPTCHA.
I load the reCAPTCHA script dynamically if it is not already loaded.
On clicking the submit button, I attempt to generate a reCAPTCHA token using grecaptcha.execute.
The generated token is then set to a hidden field and the form is submitted.

Issue:
Despite following the steps, grecaptcha.execute returns null for the token, leading to a failed reCAPTCHA validation.

Are there any issues in the way I am initializing or calling grecaptcha.execute?

Be the first to reply!

Reply