简体   繁体   中英

How to make sure that the re-captcha js file has been loaded before submitting a form?

I have a recaptcha and a registration form. Here's a simple version of a handler:

  //my_script.js

  document.getElementById("my_form").onsubmit = function(e) {
    e.preventDefault();
    grecaptcha.execute();
    var grecap_resp = grecaptcha.getResponse();
    if (grecap_resp.length !== 0) {

And the js files:

<script src="my_script.js"></script>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>

Sometimes I have to click the submit button twice. I believe it's caused by the fact that "recaptcha/api.js" hasn't been loaded yet when I'm clicking on the button. As I can see, when it's been loaded, all is working well.

How can I fix this?

As the docs say , you can pass an onload parameter with a function name that will be called when it is loaded:

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

And inside your my_script.js :

window.recaptchaLoaded = function() { // "window..." so is defined on the global scope
    console.log("Yay! captcha loaded"); // Here you should add your logic to show/enable the button that is disabled/hidden by default.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM