forked from mozilla/srihash.org
-
Notifications
You must be signed in to change notification settings - Fork 0
/
clipboard.js
51 lines (37 loc) · 993 Bytes
/
clipboard.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
44
45
46
47
48
49
50
51
"use strict";
function createNode(text) {
const node = document.getElementById('for-copy');
node.textContent = text;
return node;
}
function copyNode(node) {
if ('clipboard' in navigator) {
return navigator.clipboard.writeText(node.textContent || '');
}
const selection = getSelection();
if (selection === null) {
return Promise.reject(new Error());
}
selection.removeAllRanges();
const range = document.createRange();
range.selectNodeContents(node);
selection.addRange(range);
document.execCommand('copy');
selection.removeAllRanges();
return Promise.resolve();
}
// eslint-disable-next-line no-unused-vars
function copyText(text) {
if ('clipboard' in navigator) {
return navigator.clipboard.writeText(text);
}
const { body } = document;
if (!body) {
return Promise.reject(new Error());
}
const node = createNode(text);
body.appendChild(node);
copyNode(node);
body.removeChild(node);
return Promise.resolve();
}