简体   繁体   English

完全来自 javascript 的隐形重新验证码,无需提交表单

[英]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.我正在尝试在通过 JS 提交的表单上使用不可见的 re-captcha v2。 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.我在网上看到的每个示例都显示了一个普通的普通 HTML 提交的表单,带有指定的操作和方法,但我在表单上使用preventDefault()来使用 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: 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: 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.我见过grecaptcha.execute()但它似乎对我没有任何作用。

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.最近我遇到了像你这样的问题,让验证码不可见给我带来了很多问题,例如https://github.com/google/recaptcha/issues/269这仍然是 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). (注释代码是调用后端以使用 Google API 验证响应)。

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

Then you just use my function like this:然后你只需像这样使用我的 function :

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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