Skip to content

Commit c01895a

Browse files
authored
fix: copy error in insecure page (#535)
Signed-off-by: Bob Du <i@bobdu.cc>
1 parent 9ed2e25 commit c01895a

File tree

1 file changed

+15
-2
lines changed

1 file changed

+15
-2
lines changed

src/utils/copy.ts

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,19 @@ document.addEventListener('copy', (e) => {
66
e.preventDefault()
77
})
88

9-
export function copyToClip(text: string) {
10-
return navigator.clipboard.writeText(text)
9+
export async function copyToClip(text: string) {
10+
// https://stackoverflow.com/questions/51805395/navigator-clipboard-is-undefined
11+
if (navigator.clipboard && window.isSecureContext) {
12+
await navigator.clipboard.writeText(text)
13+
}
14+
else {
15+
const input: HTMLTextAreaElement = document.createElement('textarea')
16+
input.setAttribute('readonly', 'readonly')
17+
input.value = text
18+
document.body.appendChild(input)
19+
input.select()
20+
if (document.execCommand('copy'))
21+
document.execCommand('copy')
22+
document.body.removeChild(input)
23+
}
1124
}

0 commit comments

Comments
 (0)