0

I am attempting to integrate Google's reCaptcha v2 invisible on an existing page where the form's onsubmit handler already has a function attached that does the client-side validation. If that function returns true, the form will submit and redirect to another page.

My existing implementation does force the recaptcha validator to appear if it determines you're a bot, but immediately after the form still submits successfully and redirects to the next page.

The expected result is if the client-side validation passes, it should execute the recaptcha and display the recaptcha validator if it's heuristics deem you a bot AND prevent the form from submitting until you pass it's validator.

For reference I am testing the recaptcha via this method: https://stackoverflow.com/a/52036368/2684075

Here's the implementation

<form 
  class="elq-form"
  onsubmit="return handleFormSubmit(this)"
  ...
>
...
</form>

...

<div 
  class="g-recaptcha" 
  data-sitekey="MY_SITEKEY"
  data-callback="recaptchaOnSubmit"
  data-size="invisible"
>
</div>

<script src="https://www.google.com/recaptcha/api.js" async="" defer=""></script>

<script>
    function recaptchaOnSubmit() {
      console.log('recaptcha success');
    }

    (function() {
        var form = document.querySelector('.elq-form');
        var originalSubmit = form.onsubmit;
        form.onsubmit = null;

        form.onsubmit = function() {
          var isValid = originalSubmit.call(form);

          if (isValid) {
            window.grecaptcha.execute();
            console.log('grecaptcha executed')
          }

          return isValid;
        }

    })()
</script>
jchi2241
  • 2,032
  • 1
  • 25
  • 49

1 Answers1

0

Are you able to post the contents of handleFormSubmit() function?

I'd suggest using jQuery to handle your event, as it sounds like you're writing on top of an existing project?

The invisible version of the reCAPTCHA is version 3 right? I'm interested, are you displaying version 2, if the reCAPTCHA deems you as a bot via version 3?

$('.elq-form').submit(function () {
   // Determine if the reCAPTCHA is successful, ie, use a backend PHP script to validate
   if (response == true) {
      // return true from the form, therefore, it will proceed
      return true;
   }
   else {
      // reCAPTCHA came back as invalid, therefore do not continue.
      // We can display an error (paragraph) or anything you like
      return false;
   }
});

Also may I suggest https://developers.google.com/recaptcha/docs/v3 if you haven't checked it already? As it provides an example for the client side JS to embed.

Hope this helps,

Gareth
  • 92
  • 8