最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I call a function after grecaptcha.execute() has finished executing - triggered by an event? - Stack Overfl

programmeradmin1浏览0评论

Currently grecaptcha.execute is being executed on page load as in the first JS example below. If reCAPTCHA challenge is triggered this happens when the page has loaded. Ideally this would happen when the form submit button is clicked instead. So I've tried this by moving this into the submit event (second JS example) and put the axios function into a promise. It's submitting before grecaptcha.execute has finished executing.

What is it that I'm not understanding here? My first experience with promises so am I not understanding how promises work? Is that not the best solution for this problem? Is is something else entirely?

HTML

<head>
<script src=".js?onload=onloadCallback&render=explicit" defer></script>
</head>

JS

const form = document.querySelector('#subscribe');
let recaptchaToken;
const recaptchaExecute = (token) => {
    recaptchaToken = token;
};


const onloadCallback = () => {
    grecaptcha.render('recaptcha', {
        'sitekey': 'abcexamplesitekey',
        'callback': recaptchaExecute,
        'size': 'invisible',
    });
    grecaptcha.execute();
};

    form.addEventListener('submit', (e) => {
        e.preventDefault();
        const formResponse = document.querySelector('.js-form__error-message');
        axios({
            method: 'POST',
            url: '/actions/newsletter/verifyRecaptcha',
            data: qs.stringify({
                recaptcha: recaptchaToken,
                [window.csrfTokenName]: window.csrfTokenValue,

            }),
            config: {
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
            },
        }).then((data) => {
            if (data && data.data.success) {
                formResponse.innerHTML = '';
                form.submit();
            } else {
                formResponse.innerHTML = 'Form submission failed, please try again';
            }
        });
    }

JS

const onloadCallback = () => {
    grecaptcha.render('recaptcha', {
        'sitekey': 'abcexamplesitekey',
        'callback': recaptchaExecute,
        'size': 'invisible',
    });
};

form.addEventListener('submit', (e) => {
    e.preventDefault();
    const formResponse = document.querySelector('.js-form__error-message');
    grecaptcha.execute().then(axios({
        method: 'POST',
        url: '/actions/newsletter/verifyRecaptcha',
        data: qs.stringify({
            recaptcha: recaptchaToken,
            [window.csrfTokenName]: window.csrfTokenValue,
        }),
        config: {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
        },
    })).then((data) => {
        if (data && data.data.success) {
            formResponse.innerHTML = '';
            form.submit();
        } else {
            formResponse.innerHTML = 'Form submission failed, please try again';
        }
    });
}

Currently grecaptcha.execute is being executed on page load as in the first JS example below. If reCAPTCHA challenge is triggered this happens when the page has loaded. Ideally this would happen when the form submit button is clicked instead. So I've tried this by moving this into the submit event (second JS example) and put the axios function into a promise. It's submitting before grecaptcha.execute has finished executing.

What is it that I'm not understanding here? My first experience with promises so am I not understanding how promises work? Is that not the best solution for this problem? Is is something else entirely?

HTML

<head>
<script src="https://www.google./recaptcha/api.js?onload=onloadCallback&render=explicit" defer></script>
</head>

JS

const form = document.querySelector('#subscribe');
let recaptchaToken;
const recaptchaExecute = (token) => {
    recaptchaToken = token;
};


const onloadCallback = () => {
    grecaptcha.render('recaptcha', {
        'sitekey': 'abcexamplesitekey',
        'callback': recaptchaExecute,
        'size': 'invisible',
    });
    grecaptcha.execute();
};

    form.addEventListener('submit', (e) => {
        e.preventDefault();
        const formResponse = document.querySelector('.js-form__error-message');
        axios({
            method: 'POST',
            url: '/actions/newsletter/verifyRecaptcha',
            data: qs.stringify({
                recaptcha: recaptchaToken,
                [window.csrfTokenName]: window.csrfTokenValue,

            }),
            config: {
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
            },
        }).then((data) => {
            if (data && data.data.success) {
                formResponse.innerHTML = '';
                form.submit();
            } else {
                formResponse.innerHTML = 'Form submission failed, please try again';
            }
        });
    }

JS

const onloadCallback = () => {
    grecaptcha.render('recaptcha', {
        'sitekey': 'abcexamplesitekey',
        'callback': recaptchaExecute,
        'size': 'invisible',
    });
};

form.addEventListener('submit', (e) => {
    e.preventDefault();
    const formResponse = document.querySelector('.js-form__error-message');
    grecaptcha.execute().then(axios({
        method: 'POST',
        url: '/actions/newsletter/verifyRecaptcha',
        data: qs.stringify({
            recaptcha: recaptchaToken,
            [window.csrfTokenName]: window.csrfTokenValue,
        }),
        config: {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
        },
    })).then((data) => {
        if (data && data.data.success) {
            formResponse.innerHTML = '';
            form.submit();
        } else {
            formResponse.innerHTML = 'Form submission failed, please try again';
        }
    });
}
Share Improve this question edited Feb 26, 2019 at 3:26 DumbDevGirl42069 asked Feb 26, 2019 at 0:04 DumbDevGirl42069DumbDevGirl42069 9595 gold badges25 silver badges54 bronze badges 1
  • 2 Im not using any of the fancy stuff your doing but I had the same situation as you. You need an onclick for the form itself to excecute the captcha and return false on that onclick. Then within your reCaptcha Execute callback you need to submit your form with Javascript. – Carlitos Commented Mar 27, 2019 at 1:28
Add a ment  | 

2 Answers 2

Reset to default 1

I'm using a web service, as I wanted a method that I could use in all pages. Special attention to the fact you need to return false; and when the ajax request returns, do your post back.

<script type="text/javascript">

   function CheckCaptcha()
    {
        grecaptcha.ready(function () {
            grecaptcha.execute('<%#RecaptchaSiteKey%>', { action: 'homepage' }).then(function (token) {
            $.ajax({
                type: "POST",
                url: "../WebServices/Captcha.asmx/CaptchaVerify", 
                data: JSON.stringify({ 'captchaToken' : token }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    __doPostBack('<%= RegisterButton.UniqueID%>', '');
                    //console.log('Passed the token successfully');
                },
                failure: function (response) {                     
                    //alert(response.d);
                }
                });
            });
       });

       return false;
    }
    </script>

The way I resolved this is by changing the submit button into a dumb button, and handling everything in a js method:

@Html.HiddenFor(model => model.ReCaptchaToken);

<input type="button"
        value="Submit"
        onclick="onSubmit()"
/>

Then() method waits for the token, puts it in a hidden field, and only then manually submits the form:

<script>
    if (typeof grecaptcha == 'object') { //undefined behind the great firewall
        grecaptcha.execute('@Config.ReCaptchaSiteKey', { action: 'register' }).then(function (token) {
            window.document.getElementById('ReCaptchaToken').value = token;
            $('form').submit();
        });
    } else {
        window.document.getElementById('ReCaptchaToken').value = -1;
        $('form').submit();
    }
</script>

Note: @Html.HiddenFor is MVC - you might not use that. $('form') is JQuery - you don't necessarily need that - can use getElementById as well.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论