尝试启用 reCAPTCHA 验证时 onSubmit 事件的 JS 问题

js problem with onsubmit event when trying to enable recaptcha verification

提问人:nacer baaziz 提问时间:10/21/2023 更新时间:10/21/2023 访问量:27

问:

我正在尝试将 recaptcha 验证添加到我的网站,所以我这样做了,但我添加了一个代码以将验证添加到我的所有网站表单中,现在,我的问题是如何验证验证码,如果未成功,它必须停止事件并显示警报消息,如果成功,让表单完成 我可以通过使用form.submit())来做到这一点 但是问题,如果任何表单具有其他 onsubmit 方法,该方法可以在其他逻辑中验证或提交表单等,则在使用 form.submit()) 时,即使原始处理程序停止了该表单,它也可以提交表单, 我想解决问题

$(document).ready(function () {
  const recaptchaScript = document.createElement("script");
  recaptchaScript.src = "https://www.google.com/recaptcha/api.js?render=site_key";
  recaptchaScript.async = true;
  recaptchaScript.defer = true;
  document.head.appendChild(recaptchaScript);


  let success = false;
let event_obj = "";
  function verifyReCAPTCHAAndSubmit(form) {


    grecaptcha.ready(function () {
      grecaptcha.execute("site_key", { action: "submit" }).then(function (token) {
        if (!token) {
          alert("The reCAPTCHA token is missing or invalid. Please try again.");
          success = false;

          return false;
        }

        const xhr = new XMLHttpRequest();
        xhr.open('POST', '/services/recaptcha.php', true);
        xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        xhr.onreadystatechange = function () {
          if (xhr.readyState === 4) {
            if (xhr.status === 200) {
              const response = JSON.parse(xhr.responseText);
              if (response.success && response.score >= 0.3) {
                // reCAPTCHA verification succeeded
                success = true;
                continueFormSubmission(form);
              } else {
                alert("reCAPTCHA verification failed. Please try again.");
                success = false;

              }
            } else {
              alert("An error occurred while verifying reCAPTCHA. Please try again.");
              success = false;

            }
          }
        };
        xhr.send('response=' + token);
      });
    });
  }

  function continueFormSubmission(form) {
    // Directly invoke the form's submit method to ensure it's the last step
event_obj.returnValue = true;
alert("jj");
return true;
  }

  $('form').on('submit', function (event) {
    const form = event.target;
event_obj = event;
    verifyReCAPTCHAAndSubmit(form);
    event.preventDefault();

  });
});

JavaScript 表单 事件 onsubmit invisible-recaptcha

评论


答: 暂无答案