Uncaught Error: ReCAPTCHA placeholder element must

2020-06-12 04:48发布

I'm adding ReCAPTCHA to a (Bootstrap Jekyll) website that has multiple contact forms. There's a popup modal in the footer, an occasional "contact us now" section, and also a "request more information about ____" on several pages.

Since I have multiple contact forms on a single page, I needed to explicitly render each ReCAPTCHA. Here's the code for that:

In my javascript:

var CaptchaCallback = function() {
    grecaptcha.render('RecaptchaField1', {'sitekey' : 'my_sitekey'
    });

    grecaptcha.render('RecaptchaField2', {'sitekey' : 'my_sitekey'
    });
};

In footer (included on all pages)

<div id="RecaptchaField1"></div>

(and at the bottom of the footer)

<script src='https://www.google.com/recaptcha/api.js?onload=CaptchaCallback&render=explicit' async defer></script>

This works well on a page that has two separate contact forms (i.e. I've got another div on the page with the id of RecaptchaField2), but if I land on a page that only has one contact form, the console throws an error (Uncaught Error: ReCAPTCHA placeholder element must be an element or id).

The ReCAPTCHA seems to work anyway, but can anyone help me understand what's causing this error? All the research I've done indicates that it's from importing the library twice, but I'm assuming that's not the case, since the problem only comes up on some pages and not others.

Thank you!

3条回答
乱世女痞
2楼-- · 2020-06-12 05:32

You can also use this in pure java script way

grecaptcha.render(document.getElementById('RecaptchaField1'), {
      'sitekey' : 'my_sitekey'
    });
查看更多
▲ chillily
3楼-- · 2020-06-12 05:38

This works for me:

var CaptchaCallback = function() {
    if ( $('#RecaptchaField1').length ) {
        grecaptcha.render('RecaptchaField1', {'sitekey' : 'my_sitekey'
        });
    }
    if ( $('#RecaptchaField2').length ) {
       grecaptcha.render('RecaptchaField2', {'sitekey' : 'my_sitekey'
       });
    }
};
查看更多
太酷不给撩
4楼-- · 2020-06-12 05:44

I got the same issue and this solution didn't work for me, but I have found one.

The fact was I used the plugin wordpress Contact form 7 and , unfortunately, I have written the keys of recaptcha in the integration part.

This made the function recaptcha/api.js was called twice and made this error.

So I have just deleted the plugin and reinstall it without fill the integration part and called the recatpcha in the files header.php and footer.php and that works :)

And don't forget to put the button recaptcha in the contact form

<div class="g-recaptcha" id="YOUR-ID" data-sitekey="YOUR-KEY" render="explicit"></div>
查看更多
登录 后发表回答