I'm building an app with Angular 12 and 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).
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() : 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:
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:
ngAfterViewInit() {
const element = document.getElementsByClassName('grecaptcha-badge')[0] as HTMLElement;
if (element) {
element.style.visibility = 'visible';
}
}
and of course in OnDestroy
we hide it:
ngOnDestroy() {
if (this.recaptchaSubscription) {
this.recaptchaSubscription.unsubscribe();
}
const element = document.getElementsByClassName('grecaptcha-badge')[0] as HTMLElement;
if (element) {
element.style.visibility = 'hidden';
}
}