-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
background.js
60 lines (52 loc) · 1.39 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
'use strict';
const ADD_TEXT_ID = 'add-text';
const isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
createMenus();
function createMenus() {
let ctx = ['all'];
// Firefox support more contexts
if (isFirefox) {
ctx = ['all', 'bookmark', 'tab'];
}
chrome.contextMenus.create({
id: ADD_TEXT_ID,
title: 'Add to Text Saver',
type: 'normal',
contexts: ctx,
});
}
chrome.contextMenus.onClicked.addListener(async (item, tab) => {
let { pageUrl, srcUrl, selectionText } = item;
// when selection is null, fallback to others.
if (!selectionText) {
selectionText = srcUrl || tab.title || pageUrl;
}
let uuid = crypto.randomUUID();
const row = {
[uuid]: {
url: pageUrl,
text: selectionText,
createdAt: Date.now(),
},
};
await chrome.storage.local.set(row);
if (await getNotification()) {
await chrome.notifications.create(null, {
type: 'basic',
title: pageUrl,
contextMessage: 'Saved',
message: selectionText,
iconUrl: 'imgs/logo.png',
});
}
});
chrome.action.onClicked.addListener(function () {
chrome.runtime.openOptionsPage();
});
// Firefox doesn't support module background.js directly
// So this fn is duplicated with Options
async function getNotification() {
const key = 'enable-notification';
const opt = await chrome.storage.sync.get({ [key]: false });
return opt[key];
}