diff --git a/frontend/src/components/Captcha.jsx b/frontend/src/components/Captcha.jsx index 47d13e5..d87d826 100644 --- a/frontend/src/components/Captcha.jsx +++ b/frontend/src/components/Captcha.jsx @@ -37,27 +37,43 @@ export default function Captcha({ onToken }) { containerRef.current.innerHTML = '' - widgetIdRef.current = window.turnstile.render( - containerRef.current, - { - sitekey: TURNSTILE_SITE_KEY, - language: 'fr', - size: 'flexible', - appearance: 'always', - - callback: (token) => { - onToken(token) - }, - - 'expired-callback': () => { - onToken('') - }, - - 'error-callback': () => { - onToken('') - }, + window.turnstile.ready(() => { + if ( + cancelled || + !containerRef.current || + !window.turnstile + ) { + return } - ) + + widgetIdRef.current = window.turnstile.render( + containerRef.current, + { + sitekey: TURNSTILE_SITE_KEY, + language: 'fr', + size: 'flexible', + appearance: 'always', + + callback: (token) => { + if (!cancelled) { + onToken(token) + } + }, + + 'expired-callback': () => { + if (!cancelled) { + onToken('') + } + }, + + 'error-callback': () => { + if (!cancelled) { + onToken('') + } + }, + } + ) + }) } const existingScript = document.getElementById( @@ -66,32 +82,25 @@ export default function Captcha({ onToken }) { if (window.turnstile) { renderWidget() - return - } - - if (existingScript) { + } else if (existingScript) { existingScript.addEventListener('load', renderWidget, { once: true, }) + } else { + const script = document.createElement('script') - return () => { - cancelled = true - } + script.id = TURNSTILE_SCRIPT_ID + script.src = TURNSTILE_SCRIPT_URL + script.async = true + script.defer = true + + script.addEventListener('load', renderWidget, { + once: true, + }) + + document.head.appendChild(script) } - const script = document.createElement('script') - - script.id = TURNSTILE_SCRIPT_ID - script.src = TURNSTILE_SCRIPT_URL - script.async = true - script.defer = true - - script.addEventListener('load', renderWidget, { - once: true, - }) - - document.head.appendChild(script) - return () => { cancelled = true @@ -107,6 +116,10 @@ export default function Captcha({ onToken }) { } widgetIdRef.current = null + + if (containerRef.current) { + containerRef.current.innerHTML = '' + } } }, [onToken])