-
Notifications
You must be signed in to change notification settings - Fork 0
/
background.js
80 lines (68 loc) · 2.04 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
79
80
function start() {
chrome.browserAction.onClicked.addListener(handleExtensionButton);
chrome.webNavigation.onDOMContentLoaded.addListener(debounce(500, handleNavigation));
chrome.webNavigation.onHistoryStateUpdated.addListener(debounce(500, handleNavigation));
}
function handleExtensionButton(tab) {
console.log("clicked button", tab.id, tab.url);
getBookmarkIdForTab(tab.id, bookmarkId => {
if (bookmarkId !== null) {
console.log("tab already has a bookmark", { tabId, bookmarkId });
return;
}
console.log("create initial bookmark");
chrome.bookmarks.create(
{ parentId: "1", title: tab.title, url: tab.url },
bookmark => {
// store bookmark entry to allow reopen last url
updateBookmark(bookmark.id, tab);
// store tab/bookmark reference
chrome.storage.sync.set({ [`tab-${tab.id}`]: bookmark.id });
}
);
});
}
function debounce(time, callback) {
return (...args) => {
setTimeout(() => {
callback(...args);
}, time);
};
}
function handleNavigation(event) {
if (event.frameId !== 0) {
return;
}
console.log("its not a frame", event);
chrome.tabs.getSelected(null, tab => {
console.log("current tab", tab);
getBookmarkIdForTab(event.tabId, bookmarkId => {
console.log("got bookmark id", bookmarkId);
if (bookmarkId !== null) {
updateBookmark(bookmarkId, tab);
}
});
});
}
function getBookmarkIdForTab(tabId, callback) {
let storageKey = `tab-${tabId}`;
chrome.storage.sync.get([storageKey], storage => {
callback(storage.hasOwnProperty(storageKey) ? storage[storageKey] : null);
});
}
function updateBookmark(bookmarkId, tab) {
console.log("set bookmark entry", { bookmarkId, tab });
// update in storage
chrome.storage.sync.set({
[`bookmark-${bookmarkId}`]: {
tabId: tab.id,
url: tab.url
}
});
// update bookmark title and url
chrome.bookmarks.update(bookmarkId, {
url: chrome.runtime.getURL(`index.html#${bookmarkId}`),
title: tab.title
});
}
start();