JavaScript: Is there any way to create a separate function that returns googles recapcha token?

53 views Asked by At

Googles reCAPTCHA v3 documentation says, I have to pack all my logic that checks a token inside grecapcha.execute() function:

   <script>
      function onClick(e) {
        e.preventDefault();
        grecaptcha.ready(function() {
          grecaptcha.execute('reCAPTCHA_site_key', {action: 'submit'}).then(function(token) {
              // Add your logic to submit to your backend server here.
          });
        });
      }
  </script>

But I want to have a function that returns me the token for check like this:

let token = getToken();

So I can validate the token later. I Tried to write something like this:

function getToken(action_name = 'test'){
        grecaptcha.ready(function(){
            grecaptcha.execute(reCaptchaPublicKey, {action: action_name}).then(function(token) {
                return token;
            });
        });
}

But it doesn't work. I want to have a function that makes request to googles server to get a token. My flow must wait until function returns the token so a can later send it to my server for validation.

How can I do it? Thanks

0

There are 0 answers