代码之家  ›  专栏  ›  技术社区  ›  ruchit

如何在angular 2应用程序中添加reCAPTCHA?

  •  3
  • ruchit  · 技术社区  · 8 年前

    如何在Angular 2应用程序中集成reCAPTCHA?

    3 回复  |  直到 8 年前
        1
  •  7
  •   ruchit    8 年前

    假设您拥有reCAPTCHA提供的站点密钥和客户端机密。将下面的代码放入组件中。

    @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()
          });
        }
    }
    

    下面是成功回调函数。如果响应数据有值,则reCAPTCHA验证成功。

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

    当reCAPTCHA过期时,将调用下面的函数。

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

    将div放在HTML文件的下面。

    <div #captchaRef2></div>
    

    将JS脚本放在索引下面。html文件。

    <script src='https://www.google.com/recaptcha/api.js?render=explicit" async defer'></script>
    
        2
  •  0
  •   Faraz Ahmed    7 年前

    通过将js脚本置于上面,有时我会遇到以下错误: “grecaptcha.render不是函数” 所以,如果您遇到这个错误,只需使用下面的js脚本,而不是上面的

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

    干杯

        3
  •  0
  •   Daniel Danielecki    5 年前

    如果 ng-recaptcha 存在?

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

    2. 在您的一个模块中(例如 app.module.ts , shared.module.ts ,等等)

    (如所述 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. 在您的 html <re-captcha>