'How to dynamically update google recaptcha sitekey?

I have a plain js + jQuery app with a button protected by google recaptcha, everything works as expected, but I'm failing to update the sitekey on the fly. The reason I want this is that I have a couple of environments (staging, test, production etc.) and I'd like to have a separate sitekey for specific envs (in order to separate the test stats from data from real users).

I'm able to change the attribute on my recaptcha element, but it looks like the attributes are taken by the script on initialising the whole thing, how can I refresh/reset the widget to accept the new sitekey?

I've been experimenting with reset and render methods, but to no effect so far.

<div 
   id="google-recaptcha" 
   class="g-recaptcha" 
   data-sitekey="this-will-be-replaced-anyways" 
   data-callback="onSubmit"
   data-size="invisible"
></div>
if (grecaptcha) {
   $('#google-recaptcha').attr({
      'data-sitekey': 'my-real-sitekey'
   });
}


Solution 1:[1]

I think you are looking for Explicitly render the reCAPTCHA widget

1.Specify your onload callback function. This function will be called by JavaScript resource(see the next step)

 <script>
function onloadCallback() {
   grecaptcha.render('myCaptcha1', {
        'sitekey': 'sitekey value',  // required
        'theme': 'light',  // optional
        'callback': 'onloadCallback'  // optional
    });
}
</script>

2.Insert the JavaScript resource, setting the onload parameter to the name of your onload callback function and the render parameter to explicit.

  <script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"></script>

3.Define the target HTML control that is supposed to be a captcha on your page.

 <div id="myCaptcha1"></div>

I hope it helps you as helped me, good luck

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mohamad Bahmani