-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
253 lines (228 loc) · 6.87 KB
/
Copy pathbackground.js
File metadata and controls
253 lines (228 loc) · 6.87 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
// SyncPen Clipper - Background Service Worker
const API_BASE_URL = "https://www.syncpen.io";
// Create context menus on install
chrome.runtime.onInstalled.addListener(() => {
// Remove existing menus first
chrome.contextMenus.removeAll(() => {
// Save selection menu item
chrome.contextMenus.create({
id: "saveSelection",
title: "Save Selection to SyncPen",
contexts: ["selection"],
});
// Save image menu item
chrome.contextMenus.create({
id: "saveImage",
title: "Save Image to SyncPen",
contexts: ["image"],
});
// Save page menu item
chrome.contextMenus.create({
id: "savePage",
title: "Save Page to SyncPen",
contexts: ["page"],
});
});
});
// Handle context menu clicks
chrome.contextMenus.onClicked.addListener(async (info, tab) => {
try {
const apiKey = await getApiKey();
if (!apiKey) {
console.warn("SyncPen Clipper: API key not configured");
showNotification("Error", "Please configure your API key in the extension settings.");
return;
}
let clipData;
switch (info.menuItemId) {
case "saveSelection":
clipData = await captureSelection(tab, info.selectionText);
break;
case "saveImage":
clipData = await captureImage(tab, info.srcUrl);
break;
case "savePage":
clipData = await capturePage(tab);
break;
default:
return;
}
console.log("SyncPen Clipper: Sending clip to API...", { type: clipData.type });
const response = await sendClipToSyncPen(clipData, apiKey);
console.log("SyncPen Clipper: Clip saved successfully", response);
showNotification("Success", "Clip saved!");
} catch (error) {
console.error("SyncPen Clipper error:", error);
showNotification("Error", error.message || "Failed to save clip.");
}
});
// Get API key from storage
async function getApiKey() {
const result = await chrome.storage.sync.get(["apiKey"]);
return result.apiKey || null;
}
// Capture selected text
async function captureSelection(tab, selectionText) {
// Get additional metadata from content script
let result;
try {
[result] = await chrome.scripting.executeScript({
target: { tabId: tab.id },
func: () => ({
title: document.title,
url: window.location.href,
favicon: document.querySelector('link[rel*="icon"]')?.href || "",
description: document.querySelector('meta[name="description"]')?.content || "",
}),
});
} catch (err) {
console.error("Script injection failed:", err);
throw new Error("Cannot access this page. Try a different page.");
}
return {
type: "text",
content: selectionText,
sourceUrl: result.result.url,
sourceTitle: result.result.title,
timestamp: new Date().toISOString(),
metadata: {
favicon: result.result.favicon,
description: result.result.description,
},
};
}
// Capture image
async function captureImage(tab, imageUrl) {
let result;
try {
[result] = await chrome.scripting.executeScript({
target: { tabId: tab.id },
func: () => ({
title: document.title,
url: window.location.href,
favicon: document.querySelector('link[rel*="icon"]')?.href || "",
}),
});
} catch (err) {
console.error("Script injection failed:", err);
throw new Error("Cannot access this page. Try a different page.");
}
return {
type: "image",
content: imageUrl,
sourceUrl: result.result.url,
sourceTitle: result.result.title,
timestamp: new Date().toISOString(),
metadata: {
favicon: result.result.favicon,
},
};
}
// Capture page
async function capturePage(tab) {
let result;
try {
[result] = await chrome.scripting.executeScript({
target: { tabId: tab.id },
func: () => {
// Try to get the main content of the page
const getTextContent = () => {
// Try common content selectors
const selectors = [
"article",
"main",
'[role="main"]',
".post-content",
".article-content",
".entry-content",
"#content",
];
for (const selector of selectors) {
const element = document.querySelector(selector);
if (element) {
return element.innerText.slice(0, 2000);
}
}
// Fallback to body text
return document.body.innerText.slice(0, 2000);
};
return {
title: document.title,
url: window.location.href,
favicon: document.querySelector('link[rel*="icon"]')?.href || "",
description: document.querySelector('meta[name="description"]')?.content || "",
content: getTextContent(),
};
},
});
} catch (err) {
console.error("Script injection failed:", err);
throw new Error("Cannot access this page. Try a different page.");
}
return {
type: "page",
content: result.result.content,
sourceUrl: result.result.url,
sourceTitle: result.result.title,
timestamp: new Date().toISOString(),
metadata: {
favicon: result.result.favicon,
description: result.result.description,
},
};
}
// Send clip to SyncPen API
async function sendClipToSyncPen(clipData, apiKey) {
const baseUrl = API_BASE_URL;
const response = await fetch(`${baseUrl}/api/clipper/clip`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${apiKey}`,
},
body: JSON.stringify(clipData),
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(errorData.message || `API error: ${response.status}`);
}
return response.json();
}
// Show notification
function showNotification(title, message) {
chrome.notifications.create(
{
type: "basic",
iconUrl: chrome.runtime.getURL("icons/icon128.png"),
title: `SyncPen Clipper - ${title}`,
message: message,
},
(notificationId) => {
if (chrome.runtime.lastError) {
console.error("Notification error:", chrome.runtime.lastError);
}
}
);
}
// Listen for messages from popup
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === "testConnection") {
testConnection(request.apiKey)
.then((result) => sendResponse(result))
.catch((error) => sendResponse({ success: false, error: error.message }));
return true; // Keep channel open for async response
}
});
// Test API connection
async function testConnection(apiKey) {
const baseUrl = API_BASE_URL;
const response = await fetch(`${baseUrl}/api/clipper/clip`, {
method: "OPTIONS",
headers: {
Authorization: `Bearer ${apiKey}`,
},
});
// For OPTIONS, we just check if we can reach the endpoint
// The actual validation happens on POST
return { success: true };
}