This repository has been archived by the owner on Jan 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 128
/
clipboard.js
54 lines (50 loc) · 1.71 KB
/
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
52
53
54
/* globals catcher, assertIsBlankDocument */
"use strict";
this.clipboard = (function() {
const exports = {};
exports.copy = function(text) {
return new Promise((resolve, reject) => {
const element = document.createElement("iframe");
element.src = browser.extension.getURL("blank.html");
// We can't actually hide the iframe while copying, but we can make
// it close to invisible:
element.style.opacity = "0";
element.style.width = "1px";
element.style.height = "1px";
element.style.display = "block";
element.addEventListener("load", catcher.watchFunction(() => {
try {
const doc = element.contentDocument;
assertIsBlankDocument(doc);
const el = doc.createElement("textarea");
doc.body.appendChild(el);
el.value = text;
if (!text) {
const exc = new Error("Clipboard copy given empty text");
exc.noPopup = true;
catcher.unhandled(exc);
}
el.select();
if (doc.activeElement !== el) {
const unhandledTag = doc.activeElement ? doc.activeElement.tagName : "No active element";
const exc = new Error("Clipboard el.select failed");
exc.activeElement = unhandledTag;
exc.noPopup = true;
catcher.unhandled(exc);
}
const copied = doc.execCommand("copy");
if (!copied) {
catcher.unhandled(new Error("Clipboard copy failed"));
}
el.remove();
resolve(copied);
} finally {
element.remove();
}
}), {once: true});
document.body.appendChild(element);
});
};
return exports;
})();
null;