|
| 1 | +import { useEffect, useRef } from 'react'; |
| 2 | + |
| 3 | +const SITE_KEY = import.meta.env.VITE_TURNSTILE_SITE_KEY!; |
| 4 | + |
| 5 | +declare global { |
| 6 | + interface Window { |
| 7 | + turnstile?: any; |
| 8 | + onTurnstileOK?: (token: string) => void; |
| 9 | + onTurnstileError?: (err: unknown) => void; |
| 10 | + } |
| 11 | +} |
| 12 | + |
| 13 | +export default function TurnstileBridge() { |
| 14 | + const containerRef = useRef<HTMLDivElement | null>(null); |
| 15 | + |
| 16 | + useEffect(() => { |
| 17 | + window.onTurnstileOK = (token: string) => { |
| 18 | + window.location.href = |
| 19 | + 'ethoraappreactnative://turnstile?token=' + encodeURIComponent(token); |
| 20 | + }; |
| 21 | + |
| 22 | + window.onTurnstileError = (err: unknown) => { |
| 23 | + window.location.href = |
| 24 | + 'ethoraappreactnative://turnstile?error=' + |
| 25 | + encodeURIComponent(String(err)); |
| 26 | + }; |
| 27 | + |
| 28 | + const script = document.createElement('script'); |
| 29 | + script.src = 'https://challenges.cloudflare.com/turnstile/v0/api.js'; |
| 30 | + script.async = true; |
| 31 | + script.defer = true; |
| 32 | + script.onload = () => { |
| 33 | + if (containerRef.current && window.turnstile) { |
| 34 | + window.turnstile.render(containerRef.current, { |
| 35 | + sitekey: SITE_KEY, |
| 36 | + callback: 'onTurnstileOK', |
| 37 | + 'error-callback': 'onTurnstileError', |
| 38 | + action: 'signup', |
| 39 | + theme: 'light', |
| 40 | + }); |
| 41 | + } |
| 42 | + }; |
| 43 | + document.head.appendChild(script); |
| 44 | + |
| 45 | + return () => { |
| 46 | + document.head.removeChild(script); |
| 47 | + delete window.onTurnstileOK; |
| 48 | + delete window.onTurnstileError; |
| 49 | + }; |
| 50 | + }, []); |
| 51 | + |
| 52 | + return ( |
| 53 | + <div |
| 54 | + style={{ |
| 55 | + minHeight: '100vh', |
| 56 | + display: 'flex', |
| 57 | + alignItems: 'center', |
| 58 | + justifyContent: 'center', |
| 59 | + }} |
| 60 | + > |
| 61 | + <div ref={containerRef} /> |
| 62 | + </div> |
| 63 | + ); |
| 64 | +} |
0 commit comments