From df4a34843dc29626238755fdabe79e706826bb57 Mon Sep 17 00:00:00 2001 From: can kurttekin Date: Tue, 12 Nov 2024 04:38:52 +0300 Subject: [PATCH] turnstile component --- frontend/src/components/Register.js | 2 +- frontend/src/components/Turnstile.js | 43 ++++++++++++++++++---------- 2 files changed, 29 insertions(+), 16 deletions(-) diff --git a/frontend/src/components/Register.js b/frontend/src/components/Register.js index d785339c..7c41d67f 100644 --- a/frontend/src/components/Register.js +++ b/frontend/src/components/Register.js @@ -77,7 +77,7 @@ const Register = () => { specialChar: false, }); const [isPasswordFocused, setIsPasswordFocused] = useState(false); // Track if the password field is focused - const [turnstileToken, setTurnstileToken] = useState(''); + const [turnstileToken, setTurnstileToken] = useState(null); const navigate = useNavigate(); // Password validation function diff --git a/frontend/src/components/Turnstile.js b/frontend/src/components/Turnstile.js index 8f5d1c60..0cf955e1 100644 --- a/frontend/src/components/Turnstile.js +++ b/frontend/src/components/Turnstile.js @@ -2,25 +2,38 @@ import React, { useEffect } from 'react'; const Turnstile = ({ siteKey, onVerify }) => { useEffect(() => { - // Load the Turnstile script only once - const script = document.createElement("script"); - script.src = "https://challenges.cloudflare.com/turnstile/v0/api.js"; - script.async = true; - document.body.appendChild(script); + // Check if Turnstile script is already loaded + if (!document.querySelector("script[src='https://challenges.cloudflare.com/turnstile/v0/api.js']")) { + const script = document.createElement("script"); + script.src = "https://challenges.cloudflare.com/turnstile/v0/api.js"; + script.async = true; + script.defer = true; + document.body.appendChild(script); + } + + // Initialize Turnstile widget after script loads + const onLoad = () => { + if (window.turnstile) { + window.turnstile.render('#turnstile-widget', { + sitekey: siteKey, + callback: onVerify, + }); + } + }; + + // Check if script has already loaded + if (window.turnstile) { + onLoad(); + } else { + window.addEventListener("load", onLoad); + } return () => { - // Cleanup script when component unmounts - document.body.removeChild(script); + window.removeEventListener("load", onLoad); }; - }, []); + }, [siteKey, onVerify]); - return ( -
- ); + return
; }; export default Turnstile;