How To Add Google reCaptcha V3 Documentation

Sunil Kumar
  • Monday, February 7, 2022
  • 30 min
Debugged-Pro

Adding the Google reCAPTCHA v3 to an Angular application:

Create and configure the account on the Google reCAPTCHA

  1. Let's create an account. Access the siteGoogle Console Link => https://www.google.com/recaptcha/and click on the button v3 Admin Console.recaptcha-step1.png

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.

rte_image_8.png


3. Click on the button +. See the screenshot

rte_image_12.png


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


rte_image_11.png


6. Ready! The keys have been generated.


Create the Angular application


  1. 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
  2. Create New Service Page captcha verify service
  3. 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:

Leave a comment:

Share:
Let's Work Together

Ready to start a project?

Free Quote
Or call us now0172-4785461
Debugged-Pro
Debugged-Pro
Debugged-Pro