How to reload the google recaptcha widget after user submits invalid inputs

前端 未结 11 1628
既然无缘
既然无缘 2020-12-25 12:08

I have a registration form with the new google recaptcha widget on it. When a user submits info, we check the validation with javascript and return the problems to the page

11条回答
  •  甜味超标
    2020-12-25 12:52

    Here's some code to accompany @tzafar's answer:

    var myCaptcha = null;
    function prepCaptcha() {
        if (myCaptcha === null)
            myCaptcha = grecaptcha.render(document.getElementById('my-captcha'), {
                'sitekey': myCaptchaKey,
                'theme': 'light'
            });
        else
            grecaptcha.reset(myCaptcha);
    }
    

    In my case, my-captcha is the id of a div inside of a Bootstrap modal. I run prepCaptcha() in the event handler for the modal's shown.bs.modal event. The first time, it initializes the captcha. On subsequent shows of the modal, it resets it.

    Also, note that you can quickly verify that you're getting a new captcha by printing the completed captcha's value:

    console.log(grecaptcha.getResponse(myCaptcha));
    

    You shouldn't see the same value twice.

提交回复
热议问题