Skip to content

Instantly share code, notes, and snippets.

@velizarn
Last active July 31, 2024 12:44
Show Gist options
  • Save velizarn/771d379c63462637c866d62ae44bf16a to your computer and use it in GitHub Desktop.
Save velizarn/771d379c63462637c866d62ae44bf16a to your computer and use it in GitHub Desktop.
Multiple invisible reCAPTCHA on a single page
<title>ReCaptcha test</title>
<fieldset>
<legend>Form 1</legend>
<form method="post" action="http://httpbin.org/post" target="_blank">
<p>
<input type="text" name="form" value="form 1" size="10" />
</p>
<input type="hidden" name="captchaKey" />
<div id="captcha1" class="g-recaptcha" data-size="invisible"></div>
<p>
<button type="submit" disabled>Submit</button>
</p>
</form>
</fieldset>
<fieldset>
<legend>Form 2</legend>
<form method="post" action="http://httpbin.org/post" target="_blank">
<p>
<input type="text" name="form" value="form 2" size="10" />
</p>
<input type="hidden" name="captchaKey" />
<div id="captcha2" class="g-recaptcha" data-size="invisible"></div>
<p>
<button type="submit" disabled>Submit</button>
</p>
</form>
</fieldset>
<script type="text/javascript">
var onloadCallback = function() {
[].forEach.call(document.querySelectorAll('.g-recaptcha'), function(el){
var renderCaptcha = grecaptcha.render(el, {
sitekey: '__YOUR_SITE_KEY___',
callback: function(token) {
el.parentNode.querySelector('input[type=hidden]').value = token;
el.parentNode.querySelector('button[type="submit"]').removeAttribute('disabled');
return false;
}
});
grecaptcha.execute(renderCaptcha);
});
};
</script>
<script src='https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit&hl=en-gb' async defer></script>
<!--
https://developers.google.com/recaptcha/docs/invisible
http://prathameshsawant.com/multiple-invisible-recaptcha/?i=1
https://groups.google.com/g/recaptcha/c/7-4Q42nvfLc?pli=1
https://github.com/prathameshsawant7/multiple-invisible-recaptcha
-->
@bmiller-endertech
Copy link

I found this can popup the recaptcha challenge on page load. This is because grecaptcha.execute() is being called when the page loads. This should only be called when the form is submitted.

Below is the code I came up with based on your code. It adds a form event handler for submit, which then calls grecaptcha.execute(). I also found the hidden input name=recapKey was not needed after this change. The response can be accessed via g-recaptcha-response in the submitted form vars.

This is self contained, put it in the footer of every page with form(s) on it.

Add this to your form:
<div class="g-recaptcha" data-size="invisible" data-badge="inline"></div>

Add this to your page footer (so it appears after all form HTML is rendered). I used jQuery, but you can change to use native querySelector as needed:

<script type="text/javascript">
// note, this must use var so it's available global window object
var recaptchaOnloadCallback = function() {
    [].forEach.call(document.querySelectorAll('.g-recaptcha'), function(el){
        //console.log('init recap element: ', el);
        const jqo = $(el);
        let captchaComplete = false;
        const rcID = grecaptcha.render(el, {
            sitekey: '{{GOOGLE_INV_RECAPTCHA_SITE_KEY}}',
            callback: function(token) {
                captchaComplete = true;
                //console.log('callback executed, token:', token.substring(0,30));
                const jqoForm = jqo.closest('form');
                jqoForm.find('button[type="submit"]')
                    .html("PROCESSING...")
                    .prop('disabled', true)
                ;
                jqoForm.submit();
            }
        });
        // set up form submit event listener/handler
        jqo.closest('form').submit(function(e){
            // only do recaptch.execute() if it has not been run yet. local var tracks state.
            if (! captchaComplete) {
                e.preventDefault();
                e.stopPropagation();
                grecaptcha.execute(rcID);
                //console.log('executing grecaptcha.execute('+rcID+')');
            }
        });
    });
};
</script>
<script src='https://www.google.com/recaptcha/api.js?onload=recaptchaOnloadCallback&render=explicit' async defer></script>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment