Skip to content

Commit ddae218

Browse files
author
丁春才0668000523
committed
ui: add clipboard fallback for copy button (#34092)
1 parent bd25182 commit ddae218

File tree

1 file changed

+24
-3
lines changed

1 file changed

+24
-3
lines changed

ui/src/ui/chat/copy-as-markdown.ts

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,12 +17,33 @@ async function copyTextToClipboard(text: string): Promise<boolean> {
1717
return false;
1818
}
1919

20+
let success = false;
2021
try {
21-
await navigator.clipboard.writeText(text);
22-
return true;
22+
if (navigator.clipboard?.writeText) {
23+
await navigator.clipboard.writeText(text);
24+
success = true;
25+
}
2326
} catch {
24-
return false;
27+
// Clipboard API failed (e.g. HTTP context), try fallback
28+
}
29+
30+
// Fallback for HTTP or when Clipboard API is unavailable (secure context required)
31+
if (!success) {
32+
try {
33+
const textarea = document.createElement("textarea");
34+
textarea.value = text;
35+
textarea.style.position = "fixed";
36+
textarea.style.opacity = "0";
37+
document.body.appendChild(textarea);
38+
textarea.select();
39+
success = document.execCommand("copy");
40+
document.body.removeChild(textarea);
41+
} catch (err) {
42+
console.error("Failed to copy:", err);
43+
}
2544
}
45+
46+
return success;
2647
}
2748

2849
function setButtonLabel(button: HTMLButtonElement, label: string) {

0 commit comments

Comments
 (0)