Sahil Katia
Sahil Katia

Reputation: 63

Angular recaptcha v3, code is showing error, not able to execute the function

I am using recaptcha v3 with Angular and facing executing error.

click(){
  this.grecaptcha.execute();
  this.grecaptcha.ready('6LfwjpEUAAAAAHTtLNdC42zZZ64LM8nPqXf47vuZ', { action: 'stackblitz' })
  .then(function (token) {
      // Verify the token on the server.
      console.log(token);
  });
}

please check console of my stackblitz link

stackblitz

I used below stack question but it didn't help me out

reCAPTCHA v3 not working angular 6 - error executing.


UPDATE:

I am getting the error, ERROR Error: Cannot read property 'execute' of undefined.

in HTML I tried

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

in ts , on submit I am calling

declare const grecaptcha: any;
onsubmit(){
    this.grecaptcha.ready(() => {
     {
        this.grecaptcha.execute('6LfwjpEUAAAAAHTtLNdC42zZZ64LM8nPqXf47vuZ', {action: 'information'}).then(function(token) {
           console.log(token);
        });
     }

}) }

Upvotes: 2

Views: 4786

Answers (1)

AVJT82
AVJT82

Reputation: 73357

First note, you should post your code, since links tend to die. Secondly, when checking the documentation, it states that this is how it is called:

<script>
  grecaptcha.ready(function() {
    grecaptcha.execute('site_key', {action: 'homepage'}).then(function(token) {
       // ...
    });
  });
</script>

So you should first call grecaptcha.ready, before execute, so, like in the question you linked, declare grecaptcha outside the component and call the function in your component:

declare const grecaptcha: any;

// ...

grecaptcha.ready(() => {
  grecaptcha.execute('sitekey', { action: 'test' }).then((token) => {
    console.log(token);
  });
});

Also when looking at the grecaptcha, seems you are using some kind of test key, in v 3 you need to create your own key and add the domain in contrary with v 2 where you could try a test key provided by google.

If you are developing on localhost, add http://127.0.0.1/ as domain when you register to get your keys. Because of this restriction, I cannot "fix" the stackblitz you provided.

I tried the above code in a test project, and it worked wonderfully for me :)

Upvotes: 2

Related Questions