Handling errors with reCAPTCHA v3

Viewed 1954

I have reCAPTCHA v3 set up on my page:

<script src="https://www.google.com/recaptcha/api.js?render=MY_KEY"></script>

If internet connectivity becomes unavailable or unreliable, reCAPTCHA will insert this HTML at the bottom of my page:

<div>
  <div>
    Could not connect to the reCAPTCHA service. Please check your internet connection and reload to get a reCAPTCHA challenge.
  </div>
</div>

I would much rather handle this error in my JavaScript so I can display it to the user in a better way. However, the documentation for v3 doesn't indicate how to do this.

Any thoughts on how to catch this error?

1 Answers

You can put an onerror handler in the script tag itself:

<script src="https://www.google.com/recaptcha/api.js?render=MY_KEY" onerror="error_handler()">

But I think what you want is more along the lines of what reCAPTCHA v2 offers:

widgetId = grecaptcha.render('example1', {
    'sitekey' : 'your_site_key',
    'theme' : 'light',
    'error-callback' : error_handler()
});

I doubt that works but there is another way. You just need to monitor the DOM for changes since you know that when there is an error Google will add a div to your page. You can do that with MutationObserver.

var m = new MutationObserver(function (mutationRecords) {
    this.disconnect();
    error_handler();
});
m.observe(document.body, {childList: true});

{childList: true} tells the MutationObserver to detect nodes added to the DOM and passes them to the callback function as the parameter mutationRecords (which contains array of MutationRecord objects). From there it's up to you what to do next.

This should at least be enough to get you started!

Related