如何在注册页面显示 reCaptcha v3?

How to show reCaptcha v3 just in register page?

我正在使用 Angular 12 和 Ionic 构建应用程序。我已经使用 ng-recaptcha 包 (https://github.com/DethAriel/ng-recaptcha) which uses the Google reCaptcha v3 (https://developers.google.com/recaptcha/docs/v3) 保护了注册表。

我的问题是徽章显示在注册表单后访问的每个页面中。

例如,如果我注册该页面,我将重定向到登录页面,徽章也显示在那里。我试过像这样实现 ngOnDestroy 方法:

  ngOnDestroy() : void{
    if (this.recaptchaSubscription) {
      this.recaptchaSubscription.unsubscribe();
    }
    const element = document.getElementsByClassName('grecaptcha-badge')[0];
    if(element){
      this.renderer2.removeChild(this.document.body, element.parentElement);
    }
  }

这很好用,我被重定向到登录页面而没有显示徽章,但如果我尝试注册新用户,我就会失去验证码保护。好像没有生成验证码组件了

更新

要使用验证码,我只需像这样将服务添加到构造函数中

  constructor(...
              private recaptchaV3Service: ReCaptchaV3Service,
...) { }

然后我需要的时候就这样用

  onSubmit(): void{
    this.recaptchaSubscription = this.recaptchaV3Service.execute('registerCustomer').subscribe((recaptchaToken) => {
      //Do things 
  });

同样在我的 app.module 中,我不得不在提供者部分添加:

  providers: [
    ReCaptchaV3Service,
    { provide: RECAPTCHA_V3_SITE_KEY, useValue: environment.captchaKey }
  ],

我们在这些情况下所做的不是 从 DOM 中删除 徽章,只是切换可见性,所以 AfterViewInit - 显示徽章:

ngAfterViewInit() {
  const element = document.getElementsByClassName('grecaptcha-badge')[0] as HTMLElement;
  if (element) {
    element.style.visibility = 'visible';
  }
}

当然在 OnDestroy 中我们隐藏它:

ngOnDestroy() {
  if (this.recaptchaSubscription) {
    this.recaptchaSubscription.unsubscribe();
  }
  const element = document.getElementsByClassName('grecaptcha-badge')[0] as HTMLElement;
  if (element) {
    element.style.visibility = 'hidden';
  }
}