-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoptions.js
More file actions
89 lines (79 loc) · 2.74 KB
/
options.js
File metadata and controls
89 lines (79 loc) · 2.74 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
function isChromeApiAvailable() {
return typeof chrome !== 'undefined';
}
function getStorageSyncArea() {
if (isChromeApiAvailable() && chrome.storage && chrome.storage.sync) {
return chrome.storage.sync;
}
// Fallback shim so page opened outside extension context does not crash
return {
get(keys, callback) {
try {
const key = Array.isArray(keys)
? keys[0]
: typeof keys === 'string'
? keys
: Object.keys(keys || {})[0];
const value = key ? localStorage.getItem(key) : null;
callback && callback(key ? { [key]: value } : {});
} catch {
callback && callback({});
}
},
set(items, callback) {
try {
const entries = Object.entries(items || {});
if (entries.length) {
const [key, value] = entries[0];
if (key) localStorage.setItem(key, value);
}
} catch {}
callback && callback();
},
};
}
function flattenFolders(node, accumulator) {
if (!node) return accumulator;
if (node.url) return accumulator; // skip bookmarks; we want folders only
if (node.title !== undefined && node.id !== undefined) {
accumulator.push({ id: node.id, title: node.title || 'Untitled Folder' });
}
if (Array.isArray(node.children)) {
node.children.forEach((child) => flattenFolders(child, accumulator));
}
return accumulator;
}
function populateFolderSelect(selectedId) {
const select = document.getElementById('folderSelect');
select.innerHTML = '';
const status = document.getElementById('status');
if (!isChromeApiAvailable() || !chrome.bookmarks || !chrome.bookmarks.getTree) {
status.textContent = 'Bookmarks API unavailable. Open this page via the extension options.';
return;
}
chrome.bookmarks.getTree((trees) => {
const folders = flattenFolders(trees?.[0], []);
folders.forEach((folder) => {
const option = document.createElement('option');
option.value = folder.id;
option.textContent = `${folder.title} (id: ${folder.id})`;
if (selectedId && selectedId === folder.id) option.selected = true;
select.appendChild(option);
});
});
}
document.addEventListener('DOMContentLoaded', () => {
const storage = getStorageSyncArea();
storage.get(['selectedFolderId'], (result) => {
populateFolderSelect(result?.selectedFolderId);
});
document.getElementById('saveBtn').addEventListener('click', () => {
const select = document.getElementById('folderSelect');
const selectedFolderId = select.value;
storage.set({ selectedFolderId }, () => {
const status = document.getElementById('status');
status.textContent = 'Saved! You can close this tab.';
setTimeout(() => (status.textContent = ''), 2000);
});
});
});