-
Notifications
You must be signed in to change notification settings - Fork 20
/
copyTextToClipboard.ts
48 lines (41 loc) 路 1.17 KB
/
copyTextToClipboard.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
* Copies a piece of text to the clipboard. Adapted from [StackOverflow][1].
*
* @param {string} text The text to copy.
* @returns {Promise<boolean>} Whether the operation was successful.
*/
export async function copyTextToClipboard(text: string): Promise<boolean> {
if (navigator.clipboard) {
try {
await navigator.clipboard.writeText(text)
return true
} catch {
// Do nothing and let the remaining logic try to be successful.
}
}
const textArea = document.createElement('textarea')
// Styles for ensuring browser support
textArea.style.position = 'fixed'
textArea.style.top = '0'
textArea.style.left = '0'
textArea.style.width = '32px'
textArea.style.height = '32px'
textArea.style.padding = '0'
textArea.style.border = 'none'
textArea.style.outline = 'none'
textArea.style.boxShadow = 'none'
textArea.style.background = 'transparent'
textArea.value = text
document.body.appendChild(textArea)
textArea.focus()
textArea.select()
let isSuccess: boolean
try {
isSuccess = document.execCommand('copy')
} catch {
isSuccess = false
} finally {
document.body.removeChild(textArea)
}
return isSuccess
}