Skip to content

Commit 804c13b

Browse files
committed
fix: add clipboard fallback for code block copy in web UI
The Clipboard API (navigator.clipboard.writeText) requires a secure context (HTTPS or localhost). When the web UI is accessed over plain HTTP or on platforms without clipboard support (e.g., Termux), the copy button silently fails. Add a fallback using document.execCommand('copy') with a temporary textarea element for non-secure contexts. Fixes #1340
1 parent 94212ea commit 804c13b

1 file changed

Lines changed: 14 additions & 2 deletions

File tree

web/src/components/ai-elements/code-block.tsx

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -393,13 +393,25 @@ export const CodeBlockCopyButton = ({
393393
const { code } = useContext(CodeBlockContext);
394394

395395
const copyToClipboard = async () => {
396-
if (typeof window === "undefined" || !navigator?.clipboard?.writeText) {
396+
if (typeof window === "undefined") {
397397
onError?.(new Error("Clipboard API not available"));
398398
return;
399399
}
400400

401401
try {
402-
await navigator.clipboard.writeText(code);
402+
if (navigator?.clipboard?.writeText) {
403+
await navigator.clipboard.writeText(code);
404+
} else {
405+
// Fallback for non-secure contexts (HTTP) or older browsers
406+
const textarea = document.createElement("textarea");
407+
textarea.value = code;
408+
textarea.style.position = "fixed";
409+
textarea.style.opacity = "0";
410+
document.body.appendChild(textarea);
411+
textarea.select();
412+
document.execCommand("copy");
413+
document.body.removeChild(textarea);
414+
}
403415
setIsCopied(true);
404416
onCopy?.();
405417
setTimeout(() => setIsCopied(false), timeout);

0 commit comments

Comments
 (0)