Skip to content

Commit 981fb27

Browse files
authored
fix: add copy fallback for insecure contexts (#2044)
1 parent 885e7fd commit 981fb27

File tree

1 file changed

+18
-5
lines changed

1 file changed

+18
-5
lines changed

site/src/components/CopyButton/CopyButton.tsx

+18-5
Original file line numberDiff line numberDiff line change
@@ -29,16 +29,29 @@ export const CopyButton: React.FC<CopyButtonProps> = ({
2929
try {
3030
await window.navigator.clipboard.writeText(text)
3131
setIsCopied(true)
32-
3332
window.setTimeout(() => {
3433
setIsCopied(false)
3534
}, 1000)
3635
} catch (err) {
37-
const wrappedErr = new Error("copyToClipboard: failed to copy text to clipboard")
38-
if (err instanceof Error) {
39-
wrappedErr.stack = err.stack
36+
const input = document.createElement("input")
37+
input.value = text
38+
document.body.appendChild(input)
39+
input.focus()
40+
input.select()
41+
const result = document.execCommand("copy")
42+
document.body.removeChild(input)
43+
if (result) {
44+
setIsCopied(true)
45+
window.setTimeout(() => {
46+
setIsCopied(false)
47+
}, 1000)
48+
} else {
49+
const wrappedErr = new Error("copyToClipboard: failed to copy text to clipboard")
50+
if (err instanceof Error) {
51+
wrappedErr.stack = err.stack
52+
}
53+
console.error(wrappedErr)
4054
}
41-
console.error(wrappedErr)
4255
}
4356
}
4457

0 commit comments

Comments
 (0)