Search code examples
angularrecaptcha

How to add reCAPTCHA in angular 2 application?


How to Integrate reCAPTCHA in your Angular 2 Application?


Solution

  • Assuming that you have Site Key and Client Secret given by reCAPTCHA. Put below code in component.

    @ViewChild('captchaRef2') captchaRef2: ElementRef;
    private _reCaptchaId: number;
    private SITE_ID = [YourSiteKey];
    
    ngAfterViewInit() {
        const grecaptcha = (window as any).grecaptcha;
        if (grecaptcha) {
          this._reCaptchaId = grecaptcha.render(this.captchaRef2.nativeElement, {
            'sitekey': this.SITE_ID,
            'callback': (resonse) => this.reCapchaSuccess(resonse),
            'expired-callback': () => this.reCapchaExpired()
          });
        }
    }
    

    Below is the Success callback function. If the response data has value then reCAPTCHA verified successfully.

    reCapchaSuccess(data:any){
        if(data){
          alert("Congratulation! reCAPTCHA verified.")
          // Some logic goes here
        }
      }
    

    Below function will be called when reCAPTCHA expired.

    reCapchaExpired(){
        alert("Oops! reCAPTCHA expired.")
        // Some logic goes here
      }
    

    Put below div in the HTML file.

    <div #captchaRef2></div>
    

    Put below JS script in index.html file.

    <script src='https://www.google.com/recaptcha/api.js?render=explicit" async defer'></script>