Cannot get reCAPTCHA token onSubmit method

Viewed 1619

I have the following form and try to get token for passing it to the backend (for reCAPTCHA validation).

First, I add the necessary script to index.html:

<script src="https://www.google.com/recaptcha/api.js?render=my_site_key"></script>

Then in my login.vue form:

<a-button @click="onSubmit">Login</a-button>

<div class="g-recaptcha"
     data-sitekey="my_site_key"
     data-callback="onSubmit"
     data-size="invisible">
</div>


// ...

onSubmit() {
  var t = null;

  grecaptcha.execute().then(function(token) {
    t = token
  });
}

In onSubmit method, I cannot get token and its value is null. I tried some workarounds, but not working properly. So, is there a problem or missing part related to the implementation above? Or how can I pass the necessary parameter (I think I just need to pass token as g-recaptcha-response)?

Update:

Here is my onSubmit method. At this.login() line, it throws "Uncaught (in promise) TypeError: Cannot read property 'login' of undefined at..." error :(

onSubmit() {
  var t = null;
  grecaptcha.execute('my_site_key', {action: 'submit'}).then(function(token) {

    const payload = { email: 'admin@admin.com', password: '********' };
    this.login(payload).then((response) => {
      // ...
    });

  });
}
1 Answers

You must also pass the key and the action to the execute method.

grecaptcha.execute('reCAPTCHA_site_key', {action: 'submit'}).then(function(token) {}

Then verify the token on the backend.

Doc: https://developers.google.com/recaptcha/docs/v3

Related