-
Notifications
You must be signed in to change notification settings - Fork 1
/
copyToClipboard.js
43 lines (35 loc) · 1.07 KB
/
copyToClipboard.js
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
/**
* Copies a string of text to the user's clipboard
* @param {String} content The content within the downloaded file
* @param {Boolean} [richHtml=false]
*/
function copyToClipboard(content, richHtml = false) {
if (!richHtml && navigator.clipboard) {
return navigator.clipboard.writeText(content)
}
const activeEl = document.activeElement
const textarea = document.createElement("textarea")
textarea.style.maxHeight = "0"
textarea.style.height = "0"
textarea.style.opacity = "0"
textarea.value = content
document.body.appendChild(textarea)
textarea.select()
if (richHtml) {
const listener = e => {
e.preventDefault()
if (e.clipboardData) {
e.clipboardData.setData("text/html", content)
e.clipboardData.setData("text/plain", content)
}
}
document.addEventListener("copy", listener)
document.execCommand("copy")
document.removeEventListener("copy", listener)
} else {
document.execCommand("copy")
}
activeEl && activeEl.focus()
document.body.removeChild(textarea)
}
export default copyToClipboard