Files
THE-TIP-TOP/frontend/src/components/Captcha.jsx
Andil 361cf46905
Some checks failed
Tests / Backend - Tests skipped: 8, passed: 74
Backend Coverage #### Project Overview No changes detected, that affect the code coverage. * Line Coverage: 78.66% (553/703) * Lines of Code: 703 #### Quality Gates Summary No active quality gates.
Tests / Frontend - Lint, Tests et Build passed: 83
Frontend Coverage #### Project Overview No changes detected, that affect the code coverage. * Line Coverage: 80.20% (555/692) * Lines of Code: 692 #### Quality Gates Summary No active quality gates.
THE-TIP-TOP-MULTIBRANCH/pipeline/head There was a failure building this commit
fix: reload turnstile on SPA navigation
2026-09-20 01:53:31 +00:00

138 lines
2.9 KiB
JavaScript

import { useEffect, useRef } from 'react'
import { CAPTCHA_ENABLED, TURNSTILE_SITE_KEY } from '../config/captcha'
const TURNSTILE_SCRIPT_ID = 'cf-turnstile-script'
const TURNSTILE_SCRIPT_URL =
'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit'
export default function Captcha({ onToken }) {
const containerRef = useRef(null)
const widgetIdRef = useRef(null)
useEffect(() => {
if (!CAPTCHA_ENABLED || !TURNSTILE_SITE_KEY || !containerRef.current) {
return
}
let cancelled = false
const renderWidget = () => {
if (
cancelled ||
!containerRef.current ||
!window.turnstile
) {
return
}
if (widgetIdRef.current !== null) {
try {
window.turnstile.remove(widgetIdRef.current)
} catch {
// Widget déjà supprimé
}
widgetIdRef.current = null
}
containerRef.current.innerHTML = ''
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(
TURNSTILE_SCRIPT_ID
)
if (window.turnstile) {
renderWidget()
} else if (existingScript) {
existingScript.addEventListener('load', renderWidget, {
once: true,
})
} else {
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
if (
widgetIdRef.current !== null &&
window.turnstile
) {
try {
window.turnstile.remove(widgetIdRef.current)
} catch {
// Widget déjà supprimé
}
}
widgetIdRef.current = null
if (containerRef.current) {
containerRef.current.innerHTML = ''
}
}
}, [onToken])
if (!CAPTCHA_ENABLED || !TURNSTILE_SITE_KEY) {
return null
}
return (
<div
ref={containerRef}
id="turnstile-captcha"
className="w-full min-h-[65px] flex justify-center"
/>
)
}