Adding the Google reCAPTCHA v3 to an Angular application:
Create
and configure the account on the Google reCAPTCHA
- Let's create an account. Access the
siteGoogle Console Link =>
https://www.google.com/recaptcha/and click on the button v3 Admin Console.
2. Fill in the field Email or phone and click on the
button Next to login with your Google account and if you don't have an account, just create a new
account.
3. Click on the button +. See the screenshot
4.Fill in the field Label, click on the option
reCAPTCHA 2 check box, Fill in the field Domains, click on the checkbox Accept the reCAPTCHATerms of Service and click on the button Submit.
5. Click on the button COPY SITE KEY to copy the key, in
my case, the key (Your Capcha key) was copied because this key will be configured in the
Angular application
6. Ready! The keys have been generated.
Create
the Angular application
- Let's create the application with the Angular base structure using the @angular/cli with the route file and the SCSS style formathttps://dev.to/rodrigokamada/adding-the-bootstrap-css-framework-to-an-angular-application-2k40
- Create New Service Page captcha verify service
Then add this code
import { Injectable } from '@angular/core';
import { environment } from 'src/environments/environment';
@Injectable({
providedIn: 'root'
})
export class CaptchaVerifyService {
verifyCaptcha: any = null
//==== Captcha Verify ====
addRecaptchaScript(captcha: any) {
window['grecaptchaCallback'] = () => {
this.renderReCaptcha(captcha);
}
(function (d, s, id, obj) {
let js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) { obj.renderReCaptcha(captcha); return;}
js = d.createElement(s) as HTMLImageElement; js.id = id;
js.src = "https://www.google.com/recaptcha/api.js?onload=grecaptchaCallback&render=explicit";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'recaptcha-jssdk', this));
}
renderReCaptcha(captcha:any) {
window['grecaptcha'].render(captcha, {
'sitekey': environment.SITE_KEY,
'callback': (response: any) => {
this.verifyCaptcha = response;
}
});
}
}
3. Add login page => login.component.ts file page
@ViewChild('recaptcha', { static: true }) recaptchaElement: ElementRef;
ngOnInit() {
this.formData();
this.captcha.addRecaptchaScript(this.recaptchaElement.nativeElement);
}
4. Add Div file html page login.component.html copy and paste this code
<div class="form-group mb-4">
<div #recaptcha></div>
</div>
Thanks
Comments: