Recaptcha V3 不适用于包含多个表单的页面

Recapcha V3 doesnt work on page with multiple forms

我对 Google Recaptcha V3 有疑问。 Id 确实适用于单个表单,但如果页面中的表单多于一个表单,则仅适用于第一个表单。 如何让它适用于所有形式? 我知道问题出在 id="recaptchaResponse" 但我不知道如何解决这个问题!那里有类似的问题,但找不到解决方案。

Javascript:

<script src="https://www.google.com/recaptcha/api.js?render=key1"></script>
<script>
    grecaptcha.ready(function () {
        grecaptcha.execute('key2', { action: 'contact' }).then(function (token) {
            var recaptchaResponse = document.getElementById('recaptchaResponse');
            recaptchaResponse.value = token;
        });
    });
</script>

表格:

<form class="user" action="" method="post" name="form1" id="form1">
    <input type="hidden" name="source" value="form1">

    <button type="submit" class="btn btn-success">Submit 1</button>

    <input type="hidden" name="recaptcha_response" id="recaptchaResponse">
</form>

<form class="user" action="" method="post" name="form2" id="form2">
    <input type="hidden" name="source" value="form2">

    <button type="submit" class="btn btn-success">Submit 2</button>

    <input type="hidden" name="recaptcha_response" id="recaptchaResponse">
</form>

请帮忙!提前致谢!

问题似乎是因为 getElementById 调用只解析了第一种形式的 recaptcha_response 输入元素,而不是第二种形式。

一个简单的解决方法是将每个表单中 recaptcha_response 元素的 ID 更改为不同的内容,比如 recaptchaResponse1recaptchaResponse2。然后 Javascript 设置令牌的代码可以是:

grecaptcha.ready(function () {
  grecaptcha.execute('key2', { action: 'contact' }).then(function (token) {
    document.getElementById('recaptchaResponse1').value = token;
    document.getElementById('recaptchaResponse2').value = token;
  });
});

一种更易于维护且适用于任意数量表单的更好方法是为 recaptcha_reponse 输入指定一个 class 名称并使用 querySelectorAll 函数来获取所有具有给定 class 名称的输入并更新它们。

<form class="user" action="" method="post" name="form1" id="form1">
    <input type="hidden" name="source" value="form1">
    <button type="submit" class="btn btn-success">Submit 1</button>

    <input type="hidden" name="recaptcha_response" class="recaptchaResponse">
</form>

<form class="user" action="" method="post" name="form2" id="form2">
    <input type="hidden" name="source" value="form2">
    <button type="submit" class="btn btn-success">Submit 2</button>

    <input type="hidden" name="recaptcha_response" class="recaptchaResponse">
</form>
grecaptcha
  .execute("key", {
    action: "contact"
  })
  .then(function(token) {
    document
      .querySelectorAll(".recaptchaResponse")
      .forEach(elem => (elem.value = token))
    ;
  });

希望对您有所帮助:)

删除 id 标签并仅使用名称标签。

grecaptcha.ready(function () {
    grecaptcha.execute({publicKey}, {action: 'forms'}).then(function (token) {
        var recaptchaElements = document.getElementsByName('recaptcha');
        for (var i = 0; i < recaptchaElements.length; i++) {
            recaptchaElements[i].value = token;
        }
    });
});