Reputation: 36630
When I'm using reCAPTCHA2 in my Angular project, I use the following code to generate a captcha box (I filled site key in ofcourse in my real site):
<div class="g-recaptcha" data-sitekey="mySiteKey"></div>
This gives us the captcha like this:
However when I click on another link (implemented with Angular routerLink) and then go back the original page the CAPTCHA has disappeared.
The problem is that when implementing the captcha with
<div class="g-recaptcha" data-sitekey="mySiteKey"></div>
Google does all kinds of requests to the google servers to make the checkbox appear. Does anyone know how I could possibly solve this or point me in the right direction.
If you need more info comment, thanks.
Upvotes: 3
Views: 962
Reputation: 36630
For anyone who a similar issue here is the solution:
Google adviced to put the following link in your html header section:
<script src=\'https://www.google.com/recaptcha/api.js\'></script>
This now only gets executed when the page is loaded. When we go to another component this link isn't reloaded.
We can fix it with the following directive:
import { Directive, ElementRef, OnInit } from '@angular/core';
@Directive({
selector: '[appReCaptcha2]'
})
export class ReCaptcha2Directive implements OnInit {
constructor(private elementRef: ElementRef ) { }
ngOnInit(): void {
const fragment = document.createRange().createContextualFragment('<script src=\'https://www.google.com/recaptcha/api.js\'></script>');
this.elementRef.nativeElement.appendChild(fragment);
}
}
This creates the script on the fly and therefore we get a working reCAPTCHA. This is because now the script can load the resources from the google server necessary to render and load the reCAPTCHA
Be sure to put appReCaptcha2
directives on your forms where your want your reCAPTCHA to appear with the <div>
google provides you which looks like this:
<div class="g-recaptcha" data-sitekey="your site key provided by google"></div>
Upvotes: 1