-
Notifications
You must be signed in to change notification settings - Fork 0
/
background.js
101 lines (81 loc) · 2.34 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
const pixivId = "pixiv_bookmark";
const pixivFolderBaseName = "pixiv";
let pixivContextMenuBookmark = false;
const findFolder = async (folderBaseName) => {
const tree = await chrome.bookmarks.getTree();
return travelBookmark(
tree[0].children[0].children,
(leaf) => leaf.children && leaf.title.includes(folderBaseName)
);
};
const travelBookmark = (tree, condition) => {
let foundElement = null;
tree.map((leaf) => {
if (condition(leaf)) {
foundElement = leaf;
return;
}
if (leaf.children) {
travelBookmark(leaf.children, condition);
}
});
return foundElement;
};
setInterval(() => {
chrome.tabs.query(
{
active: true,
currentWindow: true,
},
(tabs) => {
const tab = tabs[0];
if (!tab) {
return;
}
const hostname = new URL(tab.url).hostname;
if (hostname == "www.pixiv.net" && !pixivContextMenuBookmark) {
pixivContextMenuBookmark = true;
chrome.contextMenus.create({
id: pixivId,
title: "Bookmark Image",
contexts: ["link", "selection"], // ContextType
});
}
}
);
}, 1000);
chrome.contextMenus.onClicked.addListener(async (info, tab) => {
if (!tab) {
return;
}
if (info.menuItemId == pixivId) {
const pixivFolder = await findFolder(pixivFolderBaseName);
if (!pixivFolder) {
return;
}
const numBookmarks = pixivFolder.children.length + 1;
const newTitle = `${pixivFolderBaseName} (${numBookmarks})`;
if (pixivFolder.title.includes(numBookmarks)) {
chrome.bookmarks.update(pixivFolder.id, { title: pixivFolderBaseName });
chrome.bookmarks.update(pixivFolder.id, { title: newTitle });
} else {
chrome.bookmarks.update(pixivFolder.id, { title: newTitle });
}
chrome.bookmarks.create({
parentId: pixivFolder.id,
url: info.linkUrl,
title: "Picture",
});
}
});
chrome.bookmarks.onRemoved.addListener(async (id, removeInfo) => {
const pixivFolder = await findFolder(pixivFolderBaseName);
if (!pixivFolder) {
return;
}
if (removeInfo.parentId == pixivFolder.id) {
const newTitle = `${pixivFolderBaseName} (${pixivFolder.children.length})`;
chrome.bookmarks.update(pixivFolder.id, { title: pixivFolderBaseName });
chrome.bookmarks.update(pixivFolder.id, { title: newTitle });
}
});