fire event when reCAPTCHA session expires

2019-02-04 20:15发布

I am working on google reCAPTCHA. It's working fine but when reCAPTCHA session expires after certain time and user clicks again on checkbox to fill the reCAPTCHA, google shows alert saying Error: invalid load parameters. Nothing works thereafter until user reloads the page.

The div block which contains session expired message has class rc-anchor-expired-msg. I tried div show event using this class to fire an event as soon as the session expires and tried to reset recaptcha. But this is not working either.

Is there a callback function or something using which I could reset recaptcha when session expires.

1条回答
干净又极端
2楼-- · 2019-02-04 21:09

There is an expired-callback parameter you can pass when rendering the reCAPTCHA which you can then have call the grecaptcha.reset() method.

For example:

Put this in the header.

<script>
   var callback = function() {
      grecaptcha.render('id-of-render-element', {
         'sitekey': 'your-site-key',
         'expired-callback': expCallback
       });
   };
   var expCallback = function() {
      grecaptcha.reset();
   };
</script>

Put this after the element that will be used to render the reCAPTCHA.

<div id="id-of-render-element"></div>
<script src="https://www.google.com/recaptcha/api.js?onload=callback&render=explicit" async defer></script>

This resets the reCAPTCHA every time the session expires. Got rid of the problem of the Error: invalid load parameters. alert window for me.

In case it needs explaining how it works, when the api is loaded it calls the callback function from the header script tag. This function renders the reCAPTCHA and declares the expired-callback to be the expCallback function which just resets the reCAPTCHA back to its orginal state.

You are supposed to be able to use data-expired-callback as a tag attribute when automatically rendering the reCAPTCHA (as opposed to rendering it explicitly like above) widget but the callback would not work for me when I tried it that way.

查看更多
登录 后发表回答