From 5ad49598178eb69004b6ca9cbdac056330e90a08 Mon Sep 17 00:00:00 2001 From: Xiao <65860997+xiaopeng-ye@users.noreply.github.com> Date: Tue, 1 Jul 2025 04:52:09 +0200 Subject: [PATCH] fix: enhance clipboard functionality with fallback (#264) --- src/hooks/useClipboard.ts | 36 +++++++++++++++++++++++++++++++++--- 1 file changed, 33 insertions(+), 3 deletions(-) diff --git a/src/hooks/useClipboard.ts b/src/hooks/useClipboard.ts index 9edb709..3f4c1f1 100644 --- a/src/hooks/useClipboard.ts +++ b/src/hooks/useClipboard.ts @@ -10,11 +10,41 @@ export default function useClipboard( const [hasCopied, setHasCopied] = useState(false) const onCopy = useCallback(() => { - navigator.clipboard.writeText(text).then(() => { - setHasCopied(true) - }) + if (navigator.clipboard && navigator.clipboard.writeText) { + navigator.clipboard + .writeText(text) + .then(() => { + setHasCopied(true) + }) + .catch((error) => { + console.error('Clipboard API error:', error) + fallbackCopyText(text) + }) + } else { + fallbackCopyText(text) + } }, [text]) + const fallbackCopyText = (textToCopy: string) => { + const textArea = document.createElement('textarea') + textArea.value = textToCopy + + textArea.style.position = 'absolute' + textArea.style.left = '-999999px' + + document.body.appendChild(textArea) + textArea.select() + + try { + document.execCommand('copy') + setHasCopied(true) + } catch (error) { + console.error('execCommand:', error) + } finally { + textArea.remove() + } + } + useEffect(() => { let timeoutId: NodeJS.Timeout if (hasCopied) {