-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
83 lines (75 loc) · 2.17 KB
/
background.js
File metadata and controls
83 lines (75 loc) · 2.17 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
79
80
81
82
83
// Grab background service worker: receives items and stores them.
const STORAGE_KEY = "grab_items";
const CONTEXT_MENU_ID = "grab-this";
chrome.runtime.onInstalled.addListener(() => {
// Context menu for quick capture.
chrome.contextMenus.create({
id: CONTEXT_MENU_ID,
title: "Grab This",
contexts: ["selection", "image", "link"]
});
});
chrome.contextMenus.onClicked.addListener((info, tab) => {
const payload = contextInfoToPayload(info, tab);
if (payload) {
saveItem(payload);
}
});
chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
if (!message || message.type !== "GRAB_SAVE") return;
const payload = message.payload || {};
if (!payload.source_url && _sender?.tab?.url) {
payload.source_url = _sender.tab.url;
}
if (!payload.source_title && _sender?.tab?.title) {
payload.source_title = _sender.tab.title;
}
saveItem(payload).then(() => sendResponse({ ok: true }));
return true; // Keep the message channel open for async response.
});
function contextInfoToPayload(info, tab) {
if (info.mediaType === "image" && info.srcUrl) {
return {
type: "image",
content: info.srcUrl,
source_url: info.pageUrl,
source_title: tab?.title || ""
};
}
if (info.selectionText) {
return {
type: "text",
content: info.selectionText.trim(),
source_url: info.pageUrl,
source_title: tab?.title || ""
};
}
if (info.linkUrl) {
return {
type: "text",
content: info.linkUrl,
source_url: info.pageUrl,
source_title: tab?.title || ""
};
}
return null;
}
function saveItem(payload) {
const item = {
id: Date.now(),
type: payload.type,
content: payload.content,
filename: payload.filename || "",
mime: payload.mime || "",
source_url: payload.source_url || "",
source_title: payload.source_title || "",
created_at: new Date().toISOString()
};
return new Promise((resolve) => {
chrome.storage.local.get({ [STORAGE_KEY]: [] }, (result) => {
const items = result[STORAGE_KEY] || [];
items.push(item);
chrome.storage.local.set({ [STORAGE_KEY]: items }, () => resolve(item));
});
});
}