Encountering a simple problem: some calls to refresh()
cause window.grecaptcha
to become undefined
. It doesn't happen all the time, probably due to network delays. Debugging this issue is proving to be tricky, especially since I'm still new to this concept. Any assistance or guidance on potential code errors would be greatly appreciated.
class RecaptchaController {
loadPromise;
async refresh() {
await this.load();
// window.grecaptcha is (sometimes) undefined in next line
this.element.value = window.grecaptcha.execute(this.options.siteKey, { action: 'submit' });
}
load() {
if (!this.loadPromise) {
this.context.logDebugActivity('load');
this.loadPromise = new Promise((resolve, reject) => {
const url = new URL(this.options.apiUrl);
url.searchParams.append('render', this.options.siteKey);
url.searchParams.append('hl', this.options.locale);
const script = document.createElement('script');
script.setAttribute('id', this.identifier);
script.setAttribute('src', url.toString());
// The relevant part where I'm resolving the promise
script.addEventListener('load', resolve);
script.addEventListener('error', reject);
document.body.appendChild(script);
})
}
return this.loadPromise;
}
}
An error message shows:
recaptcha_controller.js:27 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'execute')
In essence, refresh
is intended to be called within a submit
event handler, like so:
form.addEventListener('submit', async (e) => {
// This is NOT how the initialization works!
// Just an example about how I'm calling refresh()
cost recaptchaController = new RecaptchaController();
// This is actually what is happening
await recaptchaController.refresh();
// Handling submission using fetch()...
});
Omitting some code for clarity purposes and mentioning that there's a framework involved (though irrelevant).