-
Notifications
You must be signed in to change notification settings - Fork 0
/
background.js
78 lines (70 loc) · 2.63 KB
/
background.js
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
chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.create({
id: "saveLink",
title: "Add to list",
contexts: ["link"]
});
});
chrome.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId === "saveLink") {
fetchTitleAndSaveLink(info.linkUrl);
}
});
function fetchTitleAndSaveLink(url) {
fetch(url)
.then(response => response.text())
.then(html => {
const titleMatch = html.match(/<title>(.*?)<\/title>/i);
const title = titleMatch ? titleMatch[1] : url;
saveLink(url, title, false); // Add the new favorite property (false by default)
})
.catch(error => {
console.error("Error fetching page:", error);
saveLink(url, url, false); // Add the new favorite property (false by default)
});
}
function saveLink(url, title, favorite) {
chrome.storage.sync.get({ links: [] }, (data) => {
const links = data.links;
// Check for duplicate URLs
const isDuplicate = links.some(link => link.url === url);
if (isDuplicate) {
console.log("Duplicate link detected. The link will not be added.");
return; // Stop if the link is a duplicate
}
// Add the new link
links.push({ url: url, title: title, favorite: favorite });
chrome.storage.sync.set({ links: links }, () => {
if (chrome.runtime.lastError) {
console.error("Error saving link:", chrome.runtime.lastError);
} else {
console.log("Link saved successfully:", { url, title, favorite });
}
});
});
}
// Listen for messages from the popup
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === "toggleFavorite") {
const { index, favorite } = request;
toggleFavorite(index, favorite, (success) => {
sendResponse({ success }); // Ensure response is sent
});
return true; // Keep the message channel open for async response
}
});
function toggleFavorite(index, favorite, callback) {
chrome.storage.sync.get({ links: [] }, (data) => {
const links = data.links;
links[index].favorite = favorite;
chrome.storage.sync.set({ links: links }, () => {
if (chrome.runtime.lastError) {
console.error("Error updating favorite:", chrome.runtime.lastError);
callback(false); // Send false if there's an error
} else {
console.log("Favorite updated successfully");
callback(true); // Send true if success
}
});
});
}