-
Notifications
You must be signed in to change notification settings - Fork 484
/
Copy pathcopy.js
60 lines (52 loc) · 1.68 KB
/
copy.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
52
53
54
55
56
57
58
59
60
function addCopyButtonCallbacks() {
for (const el of document.getElementsByTagName("pre")) {
const button = document.createElement("button");
button.classList.add("copy-button", "fa-solid", "fa-copy");
button.setAttribute("aria-label", "Copy this code block");
button.setAttribute("title", "Copy");
el.appendChild(button);
const success = function () {
button.classList.add("success", "fa-check");
button.classList.remove("fa-copy");
};
const failure = function () {
button.classList.add("error", "fa-xmark");
button.classList.remove("fa-copy");
};
button.addEventListener("click", function () {
copyToClipboard(el.innerText).then(success, failure);
setTimeout(function () {
button.classList.add("fa-copy");
button.classList.remove("success", "fa-check", "fa-xmark");
}, 5000);
});
}
}
function copyToClipboard(text) {
// clipboard API is only available in secure contexts
if (window.navigator && window.navigator.clipboard) {
return window.navigator.clipboard.writeText(text);
} else {
return new Promise(function (resolve, reject) {
try {
const el = document.createElement("textarea");
el.textContent = text;
el.style.position = "fixed";
el.style.opacity = 0;
document.body.appendChild(el);
el.select();
document.execCommand("copy");
resolve();
} catch (err) {
reject(err);
} finally {
document.body.removeChild(el);
}
});
}
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", addCopyButtonCallbacks);
} else {
addCopyButtonCallbacks();
}