-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackground.js
52 lines (47 loc) · 1.73 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
// Where we will expose all the data we retrieve from storage.sync.
const storageCache = {};
// Asynchronously retrieve data from storage.sync, then cache it.
const initStorageCache = getAllStorageSyncData().then(items => {
// Copy the data retrieved from storage into storageCache.
Object.assign(storageCache, items);
});
// listen to the user clicking
// it's such a beautiful sound
chrome.action.onClicked.addListener(async (tab) => {
try {
await initStorageCache;
} catch (e) {
// Handle error that occurred during storage initialization.
console.log("error during storage initialization")
}
// find the tabs to snap
let tabsToSnap = await chrome.tabs.query({
currentWindow: storageCache.closeInCurrentWindowOnlySetting ? true : undefined,
pinned: storageCache.closePinnedTabsSetting ? undefined : false,
});
const tabsToSnapIds = tabsToSnap.map(({ id }) => id);
// open a new tab if the user asked for that
if (storageCache.openEmptyTabSetting) {
chrome.tabs.create({});
}
// snap them
await chrome.tabs.remove(tabsToSnapIds);
});
// Reads all data out of storage.sync and exposes it via a promise.
//
// Note: Once the Storage API gains promise support, this function
// can be greatly simplified.
function getAllStorageSyncData() {
// Immediately return a promise and start asynchronous work
return new Promise((resolve, reject) => {
// Asynchronously fetch all data from storage.sync.
chrome.storage.sync.get(null, (items) => {
// Pass any observed errors down the promise chain.
if (chrome.runtime.lastError) {
return reject(chrome.runtime.lastError);
}
// Pass the data retrieved from storage down the promise chain.
resolve(items);
});
});
}