-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
77 lines (63 loc) · 2.01 KB
/
Copy pathscript.js
File metadata and controls
77 lines (63 loc) · 2.01 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
const button = document.querySelector("#copy-btn");
const buttonShort = document.querySelector("#copy-btn-short");
const buttonCopyText = document.querySelector("#copy-btn-text");
function defaultFormatTitle(title) {
return title.replace(" - JIRA", "");
}
async function getCurrentTab() {
let queryOptions = { active: true, lastFocusedWindow: true };
// `tab` will either be a `tabs.Tab` instance or `undefined`.
let [tab] = await chrome.tabs.query(queryOptions);
return tab;
}
async function setLinkInClipboard(title, url) {
const str = `<a href="${url}">${title}</a>`;
function listener(e) {
e.clipboardData.setData("text/html", str);
e.clipboardData.setData("text/plain", str);
e.preventDefault();
}
document.addEventListener("copy", listener);
document.execCommand("copy");
document.removeEventListener("copy", listener);
}
async function setTextInClipboard(text) {
function listener(e) {
e.clipboardData.setData("text/html", text);
e.clipboardData.setData("text/plain", text);
e.preventDefault();
}
document.addEventListener("copy", listener);
document.execCommand("copy");
document.removeEventListener("copy", listener);
}
async function executeCopy(
button,
{ formatTitle = (title) => title, wrapInAnchor = true } = {}
) {
const tab = await getCurrentTab();
if (!tab) {
return;
}
const formattedTitle = defaultFormatTitle(formatTitle(tab.title));
if (wrapInAnchor) {
await setLinkInClipboard(formattedTitle, tab.url);
} else {
await setTextInClipboard(formattedTitle);
}
button.textContent = "✅ Copied!";
setTimeout(() => {
button.textContent = "Copy Link";
}, 2000);
}
button.addEventListener("click", async () => {
await executeCopy(button);
});
buttonShort.addEventListener("click", async () => {
await executeCopy(buttonShort, {
formatTitle: (title) => title.match(/\[([^\]]+)\]/)?.[0] || title,
});
});
buttonCopyText.addEventListener("click", async () => {
await executeCopy(buttonCopyText, { wrapInAnchor: false });
});