Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Primeng captcha issue with angular 6

I am using primeng captcha with angular 6 and I have an issue. When I try to directly load the page that has captcha confirmation I have this error:

ERROR TypeError: window.grecaptcha.render is not a function at Captcha.push../node_modules/primeng/components/captcha/captcha.js.Captcha.init (captcha.js:42) at Captcha.push../node_modules/primeng/components/captcha/captcha.js.Captcha.ngAfterViewInit (captcha.js:32)

I have only initialized the captcha in my index.html:

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

But it works if I route to this page from another page.

Any ideas how to solve it?

like image 621
Alessandro Celeghin Avatar asked Jun 11 '18 09:06

Alessandro Celeghin


1 Answers

I got this, so what I did was to attach the window.grecaptcha object to my component, and then *ngIf the captcha until grecaptcha.render is truthy. Check it.

// In your component
ngOnInit(){
    this.recaptcha = (window as any).grecaptcha;
}

// And then in your template
<ng-container *ngIf="recaptcha.render">
    <p-captcha ...></p-captcha>
</ng-container>

Doing this, the captcha component won't run until the script has executed and the render functions exists on the grecaptcha global.

Cheers. Best of luck to whoever finds this issue.

like image 189
frosty Avatar answered Oct 22 '22 17:10

frosty