3

i have an issue with Google Recaptcha V3. Id does work on single form but works only for first form if in page are more than 1 form. How to make it work for all forms? I know that issue is with id="recaptchaResponse" but i have no ideas how to fix this! There are smilar questions ou there but could not found a solution.

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>

Forms:

<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>

Please help! Thanks in advance!

4

2 回答 2

8

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

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

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

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

<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))
    ;
  });

希望有帮助:)

于 2019-06-11T20:40:49.400 回答
1

移除 id 标签并仅使用 name 标签。

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;
        }
    });
});

于 2020-01-30T10:21:46.083 回答