[英]How to show reCaptcha v3 just in register page?
I'm building an app with Angular 12 and Ionic.我正在使用 Angular 12 和 Ionic 构建应用程序。 I have protected the register form with the ng-recaptcha package ( https://github.com/DethAriel/ng-recaptcha ) which uses the Google reCaptcha v3 ( https://developers.google.com/recaptcha/docs/v3 ). I have protected the register form with the ng-recaptcha package ( https://github.com/DethAriel/ng-recaptcha ) which uses the Google reCaptcha v3 ( https://developers.google.com/recaptcha/docs/v3 ) .
My problem is that the badge is shown in every page visited after the register form.我的问题是徽章显示在注册表单后访问的每个页面中。
For example, If I register the page redirects me to the Login page, and the badge is shown there too.例如,如果我注册页面会将我重定向到登录页面,并且徽章也会显示在那里。 I have tried to implement the ngOnDestroy method like this:我试图像这样实现 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);
}
}
This works fine, I get redirected to the login page without showing the badge, but if I try to register a new user I loose the captcha protection.这很好用,我在不显示徽章的情况下被重定向到登录页面,但是如果我尝试注册新用户,我会失去验证码保护。 It is like the captcha component is not generated anymore.就像不再生成验证码组件一样。
UPDATE更新
To use the captcha I just add the service to the constructor like this要使用验证码,我只需像这样将服务添加到构造函数中
constructor(...
private recaptchaV3Service: ReCaptchaV3Service,
...) { }
Then I use it when I need it like this然后我在需要时使用它
onSubmit(): void{
this.recaptchaSubscription = this.recaptchaV3Service.execute('registerCustomer').subscribe((recaptchaToken) => {
//Do things
});
Also in my app.module I had to add this in the providers section:同样在我的 app.module 中,我必须在提供程序部分添加它:
providers: [
ReCaptchaV3Service,
{ provide: RECAPTCHA_V3_SITE_KEY, useValue: environment.captchaKey }
],
What we have done in these cases is not to remove the badge from the DOM, just toggling the visibility, so AfterViewInit
- display the badge:我们在这些情况下所做的不是从 DOM 中删除徽章,只是切换可见性,所以AfterViewInit
- 显示徽章:
ngAfterViewInit() {
const element = document.getElementsByClassName('grecaptcha-badge')[0] as HTMLElement;
if (element) {
element.style.visibility = 'visible';
}
}
and of course in OnDestroy
we hide it:当然在OnDestroy
我们隐藏它:
ngOnDestroy() {
if (this.recaptchaSubscription) {
this.recaptchaSubscription.unsubscribe();
}
const element = document.getElementsByClassName('grecaptcha-badge')[0] as HTMLElement;
if (element) {
element.style.visibility = 'hidden';
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.