How to add reCAPTCHA in angular 2 application?

一世执手 提交于 2021-01-04 04:28:58

问题


How to Integrate reCAPTCHA in your Angular 2 Application?


回答1:


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>



回答2:


By putting above js script, sometimes I face below error: "grecaptcha.render is not a function" so, in case you face this error just use following js script instead of above

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

cheers!




回答3:


Why overcomplicating that much if ng-recaptcha exists?

  1. yarn add ng-recaptcha or npm i ng-recaptcha --save

  2. In one of your modules (such as app.module.ts, shared.module.ts, etc.)

(like explained here)

import { RecaptchaModule, RECAPTCHA_SETTINGS, RecaptchaSettings } from 'ng-recaptcha';

@NgModule({
  imports: [RecaptchaModule],
  providers: [
    {
      provide: RECAPTCHA_SETTINGS,
      useValue: { siteKey: '<YOUR_KEY>' } as RecaptchaSettings,
    },
  ],
}) export class MyModule { }
  1. Use it in your html as <re-captcha>


来源:https://stackoverflow.com/questions/48902711/how-to-add-recaptcha-in-angular-2-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!