-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdeps.ts
53 lines (43 loc) · 1.42 KB
/
deps.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
49
50
51
52
53
/// <reference lib="dom" />
export function clipboardCopy(text: string) {
// Use the Async Clipboard API when available. Requires a secure browsing
// context (i.e. HTTPS)
if (navigator.clipboard) {
return navigator.clipboard.writeText(text).catch(function (err) {
throw err !== undefined
? err
: new DOMException("The request is not allowed", "NotAllowedError");
});
}
// ...Otherwise, use document.execCommand() fallback
// Put the text to copy into a <span>
var span = document.createElement("span");
span.textContent = text;
// Preserve consecutive spaces and newlines
span.style.whiteSpace = "pre";
span.style.webkitUserSelect = "auto";
span.style.userSelect = "all";
// Add the <span> to the page
document.body.appendChild(span);
// Make a selection object representing the range of text selected by the user
let selection = window.getSelection()!;
let range = window.document.createRange();
selection.removeAllRanges();
range.selectNode(span);
selection.addRange(range);
// Copy text to the clipboard
let success = false;
try {
success = window.document.execCommand("copy");
} catch (err) {
console.log("error", err);
}
// Cleanup
selection.removeAllRanges();
window.document.body.removeChild(span);
return success
? Promise.resolve()
: Promise.reject(
new DOMException("The request is not allowed", "NotAllowedError")
);
}