Why does calling grecaptcha.render() multiple times load Google's ReCAPTCHA library multiple times?

190 views Asked by At

I'm facing an issue where calling grecaptcha.render() more than once on the same page seems to reload Google's ReCAPTCHA library multiple times. I have two different forms on a single page and each form has its own ReCAPTCHA. However, each grecaptcha.render() call seems to initiate a new library download. Is this expected behavior, and if not, how can I resolve it?

<script
    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAmR7fIi6khfIWMHt1B4eg8KqyOnO66Vxs&callback=initMap&v=weekly&libraries=marker,places"
    defer
></script>

<script>
    function onRecaptchaLoadCallback() {
        console.log("ReCAPTCHA loaded successfully.");
        console.log(grecaptcha)
        myfunc()
    }

    function recaptchaErrorCallback() {
        console.log("An error occurred while loading ReCAPTCHA.");
    }

    function myfunc() {
        if (typeof grecaptcha !== 'undefined') { // Проверка, что ReCaptcha API загрузилась
            console.log(grecaptcha)

            if (document.getElementById('modal-captcha') !== null) {
                modalCaptcha = grecaptcha.render('modal-captcha', {
                    'sitekey': '{{ env('GOOGLE_RECAPTCHA_KEY') }}'
                });
            }

            if (document.getElementById('bottom-captcha') !== null) {
                bottomCaptcha = grecaptcha.render('bottom-captcha', {
                    'sitekey': '{{ env('GOOGLE_RECAPTCHA_KEY') }}'
                });
            }
        }

I've tried initializing ReCAPTCHA using Google's recommended async and defer attributes on the tag and an onload callback to ensure the library is ready. I was expecting the library to load once and then allow multiple grecaptcha.render() calls for different elements without re-downloading the library. But what's happening is that for each render call, the library gets downloaded again.

0

There are 0 answers