-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbackground.js
More file actions
97 lines (85 loc) · 2.78 KB
/
background.js
File metadata and controls
97 lines (85 loc) · 2.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
// Listen for messages from the server
chrome.runtime.onMessageExternal.addListener((request, sender, sendResponse) => {
if (request.token) {
// Store the token
chrome.storage.local.set({ token: request.token }, () => {
console.log("Token saved successfully in storage.");
// Confirm token was saved
chrome.storage.local.get("token", (result) => {
console.log("Retrieved token after save:", result.token);
});
// Notify popup or other parts of the extension
chrome.windows.getAll({ populate: true }, (windows) => {
windows.forEach((window) => {
window.tabs.forEach((tab) => {
chrome.runtime.sendMessage({ type: "TOKEN_UPDATED" });
});
});
});
});
// Acknowledge to the sender
sendResponse({ status: "success" });
}
});
// Track tab updates
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
// Ensure the tab update is complete and has a valid URL and title
if (changeInfo.status === "complete" && tab.url && tab.title) {
console.log("Tab updated:", tab.url);
// Prevent the popup from triggering the event
if (tab.url.includes("popup.html")) {
console.log("Ignoring popup tab update.");
return;
}
// Open the popup only if it is not already open
chrome.windows.getAll({ populate: true }, (windows) => {
const popupExists = windows.some(
(win) => win.type === "popup" && win.tabs.some((t) => t.url.includes("popup.html"))
);
if (!popupExists) {
chrome.windows.create({
url: "popup.html",
type: "popup",
width: 370,
height: 400,
});
}
});
chrome.storage.local.get("token", (data) => {
const token = data.token;
if (!token) {
console.warn("No token found in storage. Tab not sent.");
return;
}
console.log("Sending tab data with token:", token);
// Send the tab data to the backend
fetch("http://localhost:3000/api/analyze-tab", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${token}`,
},
body: JSON.stringify({
url: tab.url,
title: tab.title,
}),
})
.then((res) => res.json())
.then((data) => {
console.log("Gemini classification:", data.classification);
// Send the tab info and classification to the popup
chrome.runtime.sendMessage({
type: "TAB_ANALYZED",
data: {
url: tab.url,
title: tab.title,
classification: data.classification,
},
});
})
.catch((err) => {
console.error("Error sending tab data:", err);
});
});
}
});