提交表单时不可见的 reCaptcha 未捕获类型错误

Uncaught Type Error on Invisible reCaptcha while Form Submit

我正在尝试通过 google 实施新的隐形验证码。

但是我需要输入并且应该在 recaptcha 执行之前验证表单。

我在 recaptcha 回调函数上遇到这样的错误:

Uncaught TypeError: document.getElementById() submit is not a function

那么如何在执行验证和重新验证后提交表单?

HTML:

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

<form id="form" action="?" method="post">
     Name: (required) <input id="field" name="field">
     <div id='recaptcha' class="g-recaptcha"
          data-sitekey="6LcAmBAUAAAAAFukLQIkOIICuBBxKEdn-Gu83mcH"
          data-callback="onSubmit"
          data-size="invisible"></div>
     <button id='submit'>submit</button>
   </form>
<script>onload();</script>

Javascript:

function onSubmit(token) {
  alert('Thanks ' + document.getElementById('field').value + '!');
  document.getElementById('form').submit(); // This is error line
}

function validate(event) {
  event.preventDefault();
  if (!document.getElementById('field').value) {
    alert("Please enter your name.");
  } else {
    grecaptcha.execute();
  }
}

function onload() {
  var element = document.getElementById('submit');
  element.onclick = validate;
}

JSFiddle:http://jsfiddle.net/dp1cLh28/6/

我找到了解决方案。

问题是名为 submit (button id="submit") 的按钮 ID 与 .submit() 函数冲突。

当我更改按钮 ID 时,它起作用了!

更改按钮id:

<button id='action'>Submit</button>
            ^ submit > action or whatever

在我的例子中,我在表单中有一个输入 (type="submit") 标签而不是按钮。输入的名称与提交功能冲突。

解决方案是给输入标签起一个不同于 "submit" 的名称:

<input type="submit" name="anything-except-submit">

我必须明确命名标签,因为名称默认为类型属性中的 "submit"。

同样重要的是要注意回调只会在用户成功解决 reCAPTCHA 时调用,因此如果您的回调正在进行任何表单验证,您必须调用

grecaptcha.reset();

如果验证失败。这意味着用户将不得不再次解决reCAPTCHA,否则他将无法在更正后提交表单。

检查您的域白名单

我遇到了这个错误并且无法解决它,直到我发现错误是我没有将正确的域添加到域白名单中。

域错误没有出现在控制台上,我没有注意到页面上显示错误的选项卡(如下):