-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.ts
More file actions
46 lines (41 loc) · 1.36 KB
/
background.ts
File metadata and controls
46 lines (41 loc) · 1.36 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
import { saveItem } from "./lib/storage"
import type { GetSelectionRequest, GetSelectionResponse, SavedItem } from "./types"
const CONTEXT_ID = "anchor_save_selection"
chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.create({
id: CONTEXT_ID,
title: "Save selection to Anchor",
contexts: ["selection"]
})
})
chrome.contextMenus.onClicked.addListener(async (info, tab) => {
if (info.menuItemId !== CONTEXT_ID || !tab?.id) return
try {
const response = await chrome.tabs.sendMessage<GetSelectionRequest, GetSelectionResponse>(tab.id, { type: "GET_SELECTION" })
const now = new Date().toISOString()
const item: SavedItem = {
id: crypto.randomUUID(),
url: response?.url ?? tab.url ?? "",
title: response?.title ?? tab.title ?? "",
text: (response?.text ?? info.selectionText ?? "").trim(),
createdAt: now,
source: "contextMenu"
}
if (!item.text) return
await saveItem(item)
} catch (e) {
// no-op: content script may not be present; fallback to selectionText
const now = new Date().toISOString()
const item: SavedItem = {
id: crypto.randomUUID(),
url: tab?.url ?? "",
title: tab?.title ?? "",
text: (info.selectionText ?? "").trim(),
createdAt: now,
source: "contextMenu"
}
if (!item.text) return
await saveItem(item)
}
})
export {}