3

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?

Brad
  • 159,648
  • 54
  • 349
  • 530

1 Answers1

1

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!

PHP Guru
  • 1,301
  • 11
  • 20
  • Yes, I'm interested in the error callback like v2 has. `onerror` attribute wouldn't get what I'm looking for, and the `MutationObserver` path sounds a bit wonky. However, I did some more digging... looks like v2 and v3 are using the same script. I think that `data-error-callback` might actually work. Haven't tried it yet... will experiment more later. – Brad Oct 24 '20 at 22:17
  • If that doesn't work don't give up on MutationObserver. – PHP Guru Oct 24 '20 at 23:40
  • @Brad Where you able to find a good solution to it? I'm not able to reproduce this error but I've seen it happen to one of my customer on the session tracking software. – Whip Nov 22 '20 at 05:42
  • @VeeK Nope. `data-error-callback`/`error-callback` seems like the best bet, but I didn't try it yet. – Brad Nov 22 '20 at 06:06
  • `error-callback` is only available in v2 afaik. I've added the mutation code to my script but since I'm not able to recreate the issue (don't know how) I'm not able to test if it will work. – Whip Nov 22 '20 at 10:40