-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackground.js
56 lines (51 loc) · 2.07 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
chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.create({
id: "lookupSlang",
title: "Look Up Slang: '%s'",
contexts: ["selection"]
});
});
chrome.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId === "lookupSlang" && info.selectionText) {
const word = info.selectionText.trim();
const apiUrl = `https://api.urbandictionary.com/v0/define?term=${encodeURIComponent(word)}`;
fetch(apiUrl)
.then(response => {
if (!response.ok) {
throw new Error(`API error: ${response.status}`);
}
return response.json();
})
.then(data => {
if (data && data.list && data.list.length > 0) {
chrome.storage.local.set({ lookupResult: data.list[0].definition }, () => {
chrome.windows.create({
url: "lookup.html",
type: "popup",
width: 600,
height: 400
});
});
} else {
chrome.storage.local.set({ lookupResult: "No definitions found." }, () => {
chrome.windows.create({
url: "lookup.html",
type: "popup",
width: 600,
height: 400
});
});
}
})
.catch(error => {
chrome.storage.local.set({ lookupResult: `Error fetching the slang meaning: ${error.message}` }, () => {
chrome.windows.create({
url: "lookup.html",
type: "popup",
width: 600,
height: 400
});
});
});
}
});