Skip to content

Commit

Permalink
fix: duplicate script injection when using multiple components
Browse files Browse the repository at this point in the history
  • Loading branch information
yuskhan committed Jul 3, 2024
1 parent 3deb99b commit b4123c2
Showing 1 changed file with 12 additions and 2 deletions.
14 changes: 12 additions & 2 deletions projects/ngx-turnstile/src/lib/ngx-turnstile.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ declare global {
}
}

const SCRIPT_ID = 'ngx-turnstile';
const CALLBACK_NAME = 'onloadTurnstileCallback';
type SupportedVersion = '0';

Expand Down Expand Up @@ -83,8 +84,6 @@ export class NgxTurnstileComponent implements AfterViewInit, OnDestroy {
},
};

const script = document.createElement('script');

window[CALLBACK_NAME] = () => {
if (!this.elementRef?.nativeElement) {
return;
Expand All @@ -96,7 +95,14 @@ export class NgxTurnstileComponent implements AfterViewInit, OnDestroy {
);
};

if (this.scriptLoaded()) {
window[CALLBACK_NAME]();
return;
}

const script = document.createElement('script');
script.src = `${this._getCloudflareTurnstileUrl()}?render=explicit&onload=${CALLBACK_NAME}`;
script.id = SCRIPT_ID;
script.async = true;
script.defer = true;
document.head.appendChild(script);
Expand All @@ -114,4 +120,8 @@ export class NgxTurnstileComponent implements AfterViewInit, OnDestroy {
window.turnstile.remove(this.widgetId);
}
}

public scriptLoaded(): boolean {
return !!document.getElementById(SCRIPT_ID);
}
}

0 comments on commit b4123c2

Please sign in to comment.