sdsd
sdsd

Reputation: 517

How can i use recaptcha v3 in Angular?

I know there are some ng captcha libraries out there. I didn't wanted just for one method call to install npm dependency. In the pure java script implementation for example onSubmit method call, when we submit the form we call this method from the google recaptcha api

 recaptcha.execute(secret_key, {action: 'homepage'}).then(function(token) {
       c.log('token', token);
})

but i can't find a way, how can i tell angular and typescript that this recaptcha variable is from the google api and it will execute the execute method.

Now ofcourse i get the error

 recaptcha.execute is not a function

Have somoene found a way without library ?

Upvotes: 2

Views: 4450

Answers (1)

sdsd
sdsd

Reputation: 517

So this is the way

app.component.ts


declare var grecaptcha: any;
const siteKey = 'YOUR_SITE_KEY';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
 
onSubmit() {
    grecaptcha.ready(() => {
      grecaptcha.execute(siteKey, { action: 'contactUs' }).then((token) => {
        console.log(token);
        let body = {
          firstName:this.firstName,
          captcha:token
        }
        this.recapService.checkRecaptcha(body).subscribe(res => {
          console.log('res', res);
        })
      });
    });
  }

}

service

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class RecapService {

  constructor(private http: HttpClient) { }

  checkRecaptcha(body) {
    return this.http.post('http://localhost:3000/subscribe', body);
  }
}

Upvotes: 2

Related Questions