Reputation: 75
I am trying to implement recaptcha in my project, but I'm not sure how to use it.
I'm importing script in this way:
public loadScript() {
let body = <HTMLDivElement>document.body;
let script = document.createElement('script');
script.innerHTML = '';
script.src = 'https://www.google.com/recaptcha/api.js';
script.async = true;
script.defer = true;
body.appendChild(script);
}
Then I call this function in component constructor, and it works - recaptcha is properly rendered and works, but how to get response for my backend from it?
I tried grecaptcha.getResponse()
but I get ReferenceError: "grecaptcha is not defined"
- what is interesting not always. So how to make Typescript know what grecaptcha is?
Upvotes: 1
Views: 4629
Reputation: 677
To Use Google reCAPTCHA v3 in Angular 4,5,6 follow the simple steps
Register For the public key on Google official Recaptcha website
Now Add following script file in your angular project index.html
<script src='https://www.google.com/recaptcha/api.js'></script>
Then add the following tag in your Component file where you want to use Captcha
<div class="form-group">
<div id="captcha_element" class="g-recaptcha"
[attr.data-sitekey]="siteKeyCaptcha"></div>
</div>
Now update your Typescript file with the following code.
declare var grecaptcha: any;
//declare Varible with public key given by Google
siteKeyCaptcha: string = "6LdF6xxxxxxxxxxxxxxxxxxxxxxxxxxxWVT";
//when we route back from the page we have to render captcha again
grecaptcha.render('capcha_element', {
'sitekey': this.siteKeyCaptcha
});
To get a Response from Captcha on click add call back event as follows in HTML
**HTML**
<div class="form-group">
<div id="capcha_element" class="g-recaptcha"
data-callback="getResponceCapcha" [attr.data-sitekey]="siteKeyCaptcha"></div>
</div>
**Typescript**
ngOnInit() {
//....rest of code....
window['getResponceCapcha'] = this.getResponceCapcha.bind(this);
}
getResponceCapcha(captchaResponse: string) {
this.verifyCaptcha(captchaResponse);
}
verifyCaptcha(captchaResponse: string) {
//you can do HTTP call from here
}
Upvotes: 5