-
Notifications
You must be signed in to change notification settings - Fork 41
fix: add clipboard fallback for copy actions #66
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,50 @@ | ||
| export async function copyToClipboard(value: string): Promise<void> { | ||
| if (!value) throw new Error("No value to copy") | ||
|
|
||
| if (typeof navigator !== "undefined" && navigator.clipboard?.writeText) { | ||
| try { | ||
| await navigator.clipboard.writeText(value) | ||
| return | ||
| } catch (error) { | ||
| // Fallback to legacy copy only when Clipboard API is denied or unsupported in current context | ||
| const fallback = legacyCopyToClipboard(value) | ||
| if (fallback) return | ||
| if (error instanceof Error) throw error | ||
| throw new Error("Failed to copy text") | ||
| } | ||
| } | ||
|
|
||
| const fallback = legacyCopyToClipboard(value) | ||
| if (fallback) return | ||
|
|
||
| throw new Error("Failed to copy text") | ||
| } | ||
|
|
||
| function legacyCopyToClipboard(value: string): boolean { | ||
| if (typeof document === "undefined" || !document?.execCommand) return false | ||
|
|
||
| const textarea = document.createElement("textarea") | ||
| textarea.value = value | ||
| textarea.setAttribute("readonly", "") | ||
| textarea.style.position = "fixed" | ||
| textarea.style.top = "0" | ||
| textarea.style.left = "0" | ||
| textarea.style.opacity = "0" | ||
| textarea.style.pointerEvents = "none" | ||
| textarea.style.zIndex = "-1" | ||
|
|
||
| document.body.appendChild(textarea) | ||
| textarea.focus() | ||
| textarea.select() | ||
|
|
||
| let copied = false | ||
| try { | ||
| copied = document.execCommand("copy") | ||
| } catch { | ||
| copied = false | ||
| } finally { | ||
| document.body.removeChild(textarea) | ||
| } | ||
|
Comment on lines
+36
to
+47
|
||
|
|
||
| return copied | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The comment says the legacy path is used "only when Clipboard API is denied or unsupported", but the code falls back on any
navigator.clipboard.writeTexterror. Either narrow the fallback condition (e.g., specific error names) or adjust the comment to match actual behavior.