verto-health / ngx-turnstile

Cloudflare Turnstile for Angular
https://ngx-turnstile.pages.dev/
MIT License
62 stars 13 forks source link

Check that turnstile was loaded before calling remove during onDestroy #7

Closed piprees closed 1 year ago

piprees commented 1 year ago

Hi there. Great library!

Noticed a console error: Cannot read properties of undefined (reading 'remove')

Which is caused by this method in src/lib/ngx-turnstile.component.ts:

  public ngOnDestroy(): void {
    window.turnstile.remove(this.widgetId);
  }

We do a lot of lazy loading and generally don't load many modules in our root component.

When the user logs in and our signup modal gets destroyed (which contains this widget), the onDestroy method is called which subsequently calls window.turnstile.remove.

The problem in our case is that turnstile hasn't actually been loaded yet, so this pull request adds a check to make sure the widget id exists (which seems to indicate that the callback has fired) before calling window.turnstile.remove:

  public ngOnDestroy(): void {
    if (this.widgetId) {
      window.turnstile.remove(this.widgetId);
    }
  }

Happy to make any changes.