如何检查用户在 Google recaptcha 中选中复选框的 js?

How to check in js that user has checked the checkbox in Google recaptcha?

我在 head 结束前添加了以下内容

<script src='https://www.google.com/recaptcha/api.js'></script>

我在表格结束前添加了这个

<div class="g-recaptcha" data-sitekey="== xxxxxx =="></div>

我可以看到类似于https://developers.google.com/recaptcha/

的recaptcha

但是,当用户在没有选中复选框的情况下按下数据时,数据将被提交。我是否需要添加任何其他代码来检查用户是否按下了复选框?希望在 js 中?

Google 有一个复选框被选中时的回调选项。

将此添加到您的表单元素中:

data-callback="XXX"

示例:

<div class="g-recaptcha" data-callback="recaptchaCallback" data-sitekey="== xxxxxx =="></div>

以及您的提交按钮的禁用属性。

示例:

<button id="submitBtn" disabled>Submit</button>

然后创建回调函数并编写您需要的任何代码。

示例:

function recaptchaCallback() {
    $('#submitBtn').removeAttr('disabled');
};

您也可以调用grecaptcha对象来查看。 grecaptcha.getResponse();不勾选时为空,勾选时有验证码。

grecaptcha.getResponse().length === 0 未选中时

function isCaptchaChecked() {
  return grecaptcha && grecaptcha.getResponse().length !== 0;
}

if (isCaptchaChecked()) {
  // ...
}

让浏览器为您完成这项工作! (基于 slinky2000 的回答)

注意: 这只是为了防止发送 'accidentally' 未经检查的重新验证。 你仍然需要在服务器端验证 recaptcha 因为机器人不关心......

div.g-recaptcha.

下方添加一个带有 required=true 属性的不可见输入标签
<input id='recaptcha_check_empty' required tabindex='-1',
style='width:50px; height:0; opacity:0; pointer-events:none; 
position:absolute; 
bottom:0;'>

position=relative; 将宽度 a div 括起来,将上面的 bottom:0; 指向 recaptcha 的底部。

现在浏览器会很好地要求填写此字段 - 指向 recapcha。

现在我们需要回调:

<div class="g-recaptcha" data-callback="recaptchaCallback" ...

function recaptchaCallback() { 
    $('#recaptcha_check_empty').val(1);
}

要检查 google recaptcha 是否被选中,您可以通过以下代码完成:

<script>

if(grecaptcha && grecaptcha.getResponse().length > 0)
{
     //the recaptcha is checked
     // Do what you want here
     alert('Well, recaptcha is checked !');
}
else
{
    //The recaptcha is not cheched
    //You can display an error message here
    alert('Oops, you have to check the recaptcha !');
}

</script>

要检查 google recaptcha v2 是否被选中,您可以通过以下代码完成:

var checkCaptch = false;
     var verifyCallback = function(response) {
        if (response == "") {
             checkCaptch = false;
         }
         else {
             checkCaptch = true;
         }
     };
     $(document).ready(function() {
         $("#btnSubmit").click(function() {
             if (checkCaptch && grecaptcha.getResponse()!="") {
                  //Write your success code here
             }
         });
     })
<div class="contact-inner contact-message">
  <label for="message-text" class="col-form-label">CAPTCHA</label>
  <div class="g-recaptcha" data-sitekey="<?php echo 6LfSJmocAAAAAFFMpMKB1CtYNJYDyDswO7GpxRXS ;?>">
  </div>
</div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src='https://www.google.com/recaptcha/api.js'></script>
<!DOCTYPE html>
<html>
  <head>
    <title>CAPTCHA</title>
  </head>
  <body>
      <div class="contact-inner contact-message">
        <label for="message-text" class="col-form-label">CAPTCHA</label>
        <div class="g-recaptcha" data-sitekey="<?php echo GOOGLE_KEY ;?>"></div>
      </div>
  </body>
</html>

如果出于某种原因,您像我一样手动调节表格,​​并且 required 不起作用。

首先导入 ReCAPTCHA

import  ReCAPTCHA  from 'react-google-recaptcha'

在你的组件中应用它

<ReCAPTCHA style={{margin: '5px', transform: 'scale(0.8)'}} ref={recaptchaRef} sitekey={recaptchaKey} onChange={updateRecaptcha}/>

您可以使用 useRef 或只使用您导入的 ReCAPTCHA,我使用 useRef

const recaptchaRef = useRef<any>()

现在,如何检查 recaptchaRef 是否被选中?

if (recaptchaRef.current.props.grecaptcha.getResponse().length !== 0) {
    //your condition
}

基本上,你是在说 'if recaptcha is true, then do this'

这是对您有帮助的完整表单代码(我使用的是 typeScipt)

const Formid = // yout formid
const FormSpark = `https://submit-form.com/${Formid}`

type FormState =  {
    name: string,
    mail: string,
    message: string
}
const initialState = {
    name: '',
    mail: '',
    message: '',
}

const [wrongmail, setWrongmail] = useState(false)
const [wrongname, setWronname] = useState(false)
const [wrongtext, setWrongtext] = useState(false)
const [alert, setAlert] = useState(false)
const recaptchaRef = useRef<any>()
const recaptchaKey = //your recaptcha public key    const [recaptchaToken, setRecaptchaToken] = useState<string>()
const [formstate, setFormState] = useState<FormState>(initialState)
const submit = async(event: FormEvent) =>{
    event.preventDefault()
    await postSubmission()
}
const updateRecaptcha = (token: string | null)=>{
    setRecaptchaToken(token as string)
}
const {name, mail, message} = formstate
const postSubmission = async() => {
    const payload = {
        ...formstate,
        "g-recaptcha-response": recaptchaToken
    }
    try {
        if (name && mail && message) {
            if (mail.includes('@') && mail.includes('.') && mail.length > 5) {
                if (name.includes(' ') && name.length> 5) {
                    if (message.length > 20) {
                        if (recaptchaRef.current) {
                            if (recaptchaRef.current.props.grecaptcha.getResponse().length !== 0) {
                                console.log('hola')
                                setAlert(true)
                                const result = await axios.post(FormSpark, payload)
                                setFormState(initialState)
                                recaptchaRef.current.reset()
                                if (result) {
                                    setTimeout(() => {
                                        setAlert(false)
                                    },2000)
                                }
                            }
                        }
                    }
                }
            }
            if (!name && !(name.length> 5) && !(name.includes(' '))) {
                setWronname(true)
                setTimeout(() => {
                    setWronname(false)
                },3000)
            }
            if (!mail && !mail.includes('@') && !mail.includes('.') && !(mail.length > 5)) {
                setWrongmail(true)
                setTimeout(()=>{
                    setWrongmail(false)
                },3000)
            }
            if (!message && !(message.length > 20)) {
                setWrongtext(true)
                setTimeout(() => {
                    setWrongtext(false)
                },3000)
            }
        }
    } catch(error){
        console.log(error);
    }
}

const updateForm = (event: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const {id, value} = event.target
    const formKey = id as keyof FormState
    const updatedFormState = {...formstate}
    updatedFormState[formKey] = value
    setFormState(updatedFormState)
}