简体   繁体   中英

Invisible re-captcha fully from javascript without form submission

I am trying to use an invisible re-captcha v2 on a form that is submitted through JS. Every example I see online shows a regular plain HTML submitted form with a specified action and method, but I am using preventDefault() on my form to submit it with ajax. It seems like such a simple thing but I've been searching for hours and can't find a single person online who has ever done this.

HMTL:

<form id="form-login">
  <!-- ...form fields... -->

  <div
      class="g-recaptcha"
      data-sitekey="<site_key>"
      data-size="invisible"
    ></div>
  <button class="uk-button uk-button-primary" type="submit">Submit</button>
</form>

JS:

$('#form-login').submit(function(event) {
  event.preventDefault();

  console.log(grecaptcha.getResponse()); // <-- always comes back empty
});

I can see that the captcha is initializing because I can see the icon in the bottom right.

I've seen grecaptcha.execute() but it doesn't seem to do anything for me.

There are no errors in the console.

Recently I had a problem like you, making captcha invisible created a lot of issues for me eg https://github.com/google/recaptcha/issues/269 which is still an opened issue on GitHub.

I solved it with dynamically genarated captcha on each time form is submitted. Here is a bit of code I used. (commented code is a call to backend to verify response with Google API).

https://gist.github.com/ANTOSzbk/75ed7003e914162550f61399122a3bd4

Then you just use my function like this:

$('#form-login').submit(async function(event) {
  event.preventDefault();
  const response = await captchaVerification();
  if (response) { } // proper submit code execution
  else { } // on invalid captcha response
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM