-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.ts
More file actions
78 lines (70 loc) · 1.78 KB
/
background.ts
File metadata and controls
78 lines (70 loc) · 1.78 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
78
import type { PlasmoCSConfig } from "plasmo"
import {
COMMANDS,
storage,
STORE_KEYS,
type OptionType
} from "~constant/index"
import {
formatCustomTabInfo,
formatFullTabInfo,
formatMarkdownTabInfo,
getTabInfoFromTab
} from "~utils/tab-format"
export const config: PlasmoCSConfig = {
matches: ["<all_urls>"]
}
function handleCommand(command: string) {
chrome.tabs.query({ active: true, currentWindow: true }, async (tabs) => {
const tab = tabs[0]
const tabInfo = getTabInfoFromTab(tab)
if (tab?.id == null || !tabInfo || tabInfo.protocol.startsWith("chrome")) {
return
}
let text = ""
switch (command) {
case COMMANDS.COPY_TAB_INFO:
text = formatFullTabInfo(tabInfo)
break
case COMMANDS.COPY_TAB_INFO_MARKDOWN:
text = formatMarkdownTabInfo(tabInfo)
break
case COMMANDS.COPY_TAB_INFO_CUSTOM:
text = formatCustomTabInfo(
tabInfo,
await storage.get<Partial<OptionType>>(STORE_KEYS)
)
break
default:
return
}
copyTextToClipboard(tab.id, text)
})
}
chrome.commands.onCommand.addListener(handleCommand)
function copyTextToClipboard(tabId: number, text: string) {
if (!text) {
return
}
chrome.scripting.executeScript(
{
target: { tabId: tabId },
func: (copyText) => {
const textArea = document.createElement("textarea")
textArea.value = copyText
document.body.appendChild(textArea)
textArea.select()
document.execCommand("copy")
document.body.removeChild(textArea)
},
args: [text]
},
() => {
if (chrome.runtime.lastError) {
console.error(
"Script execution failed: " + chrome.runtime.lastError.message
)
}
}
)
}