[javascript] How to Reload ReCaptcha using JavaScript?

I have a signup form with AJAX so that I want to refresh Recaptcha image anytime an error is occured (i.e. username already in use).

I am looking for a code compatible with ReCaptcha to reload it using JavaScript.

This question is related to javascript recaptcha

The answer is


Try this

<script type="text/javascript" src="//www.google.com/recaptcha/api/js/recaptcha_ajax.js"></script>
<script type="text/javascript">
          function showRecaptcha() {
            Recaptcha.create("YOURPUBLICKEY", 'captchadiv', {
              theme: 'red',
              callback: Recaptcha.focus_response_field
            });
          }
 </script>

<div id="captchadiv"></div>

If you calll showRecaptcha the captchadiv will be populated with a new recaptcha instance.


Or you could just simulate a click on the refresh button

// If recaptcha object exists, refresh it
    if (typeof Recaptcha != "undefined") {
      jQuery('#recaptcha_reload').click();
    }

if you are using new recaptcha 2.0 use this: for code behind:

ScriptManager.RegisterStartupScript(this, this.GetType(), "CaptchaReload", "$.getScript(\"https://www.google.com/recaptcha/api.js\", function () {});", true);

for simple javascript

<script>$.getScript(\"https://www.google.com/recaptcha/api.js\", function () {});</script>

For AngularJS users:

$window.grecaptcha.reset();

grecaptcha.reset(opt_widget_id)

Resets the reCAPTCHA widget. An optional widget id can be passed, otherwise the function resets the first widget created. (from Google's web page)


If you are using version 1

Recaptcha.reload();

If you are using version 2

grecaptcha.reset();

For reCaptcha v2, use:

grecaptcha.reset();

If you're using reCaptcha v1 (probably not):

Recaptcha.reload();

This will do if there is an already loaded Recaptcha on the window.

(Updated based on @SebiH's comment below.)