-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoffscreen.js
More file actions
44 lines (37 loc) · 1.02 KB
/
offscreen.js
File metadata and controls
44 lines (37 loc) · 1.02 KB
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
async function copyText(text) {
try {
await navigator.clipboard.writeText(text);
return;
} catch (error) {
const textarea = document.createElement("textarea");
textarea.value = text;
textarea.setAttribute("readonly", "");
textarea.style.position = "fixed";
textarea.style.opacity = "0";
document.body.appendChild(textarea);
textarea.focus();
textarea.select();
textarea.setSelectionRange(0, textarea.value.length);
const success = document.execCommand("copy");
document.body.removeChild(textarea);
if (!success) {
throw error || new Error("document.execCommand('copy') failed.");
}
}
}
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message?.type !== "copy-to-clipboard") {
return;
}
copyText(message.text)
.then(() => {
sendResponse({ ok: true });
})
.catch((error) => {
sendResponse({
ok: false,
error: error?.message || "Clipboard copy failed."
});
});
return true;
});