-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackground.js
75 lines (71 loc) · 1.92 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
let selectedWord = "";
let def = "";
let searchWord = "";
async function logJSONData(str) {
const response = await fetch(
`https://api.dictionaryapi.dev/api/v2/entries/en/${str}`
);
console.log(response.status);
if (response.status === 200) {
const jsonData = await response.json();
const def = jsonData[0].meanings[0].definitions[0].definition;
return def;
} else {
return null;
}
}
chrome.runtime.onInstalled.addListener(function () {
chrome.contextMenus.create({
title: 'Define "%s"',
contexts: ["selection"],
id: "defineContextMenu",
});
});
chrome.contextMenus.onClicked.addListener(async function (info, tab) {
if (info.menuItemId === "defineContextMenu") {
selectedWord = info.selectionText;
searchWord = selectedWord;
def = await logJSONData(selectedWord);
if (!def) {
selectedWord = "No Definitions Found";
def =
"Sorry pal, we couldn't find definitions for the word you were looking for.";
} else {
selectedWord =
selectedWord.charAt(0).toUpperCase() + selectedWord.substring(1);
}
chrome.notifications.create(
{
type: "basic",
iconUrl: "icons/icon-32.png",
title: selectedWord,
message: def,
requireInteraction: true,
buttons: [
{
title: "Search on Google",
},
{
title: "Close",
},
],
},
(notificationId) => {
console.log("Notification created with ID:", notificationId);
}
);
}
});
chrome.notifications.onButtonClicked.addListener(
(notificationId, buttonIndex) => {
if (buttonIndex === 0) {
chrome.tabs.create({
url: `https://www.google.com/search?q=define+${searchWord}`,
});
} else if (buttonIndex === 1) {
chrome.notifications.clear(notificationId, () =>
console.log("CLosed notification", notificationId)
);
}
}
);