Skip to content

Commit 3185546

Browse files
committed
remove turnstile callback function after load or error
1 parent 01cc403 commit 3185546

File tree

2 files changed

+12
-6
lines changed

2 files changed

+12
-6
lines changed

HISTORY.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
77

88
## [Unreleased]
99

10+
### Changed
11+
12+
- Temporary load callback function is now removed after load
13+
1014
## [1.0.6] - 2022-11-25
1115

1216
### Added

src/index.tsx

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
import React, { useEffect, useState, useRef } from "react";
22
import { TurnstileOptions } from "turnstile-types";
33

4-
const global = globalThis ?? window;
4+
const global = (globalThis ?? window) as any;
55
let turnstileState =
6-
typeof (global as any).turnstile !== "undefined" ? "ready" : "unloaded";
6+
typeof global.turnstile !== "undefined" ? "ready" : "unloaded";
77
let ensureTurnstile: () => Promise<any>;
88

99
// Functions responsible for loading the turnstile api, while also making sure
@@ -20,20 +20,22 @@ let ensureTurnstile: () => Promise<any>;
2020
turnstileLoad = { resolve, reject };
2121
if (turnstileState === "ready") resolve(undefined);
2222
});
23-
(global as any)[TURNSTILE_LOAD_FUNCTION] = () => {
24-
turnstileLoad.resolve();
25-
turnstileState = "ready";
26-
};
2723

2824
ensureTurnstile = () => {
2925
if (turnstileState === "unloaded") {
3026
turnstileState = "loading";
27+
global[TURNSTILE_LOAD_FUNCTION] = () => {
28+
turnstileLoad.resolve();
29+
turnstileState = "ready";
30+
delete global[TURNSTILE_LOAD_FUNCTION];
31+
};
3132
const url = `${TURNSTILE_SRC}?onload=${TURNSTILE_LOAD_FUNCTION}&render=explicit`;
3233
const script = document.createElement("script");
3334
script.src = url;
3435
script.async = true;
3536
script.addEventListener("error", () => {
3637
turnstileLoad.reject("Failed to load Turnstile.");
38+
delete global[TURNSTILE_LOAD_FUNCTION];
3739
});
3840
document.head.appendChild(script);
3941
}

0 commit comments

Comments
 (0)