This repository has been archived by the owner on Dec 18, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
background.js
125 lines (103 loc) · 3.64 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
(function () {
var dictionarySettings = {
theme: {
value: "auto", //light/dark/auto
},
};
function getDefinition(data, callback) {
var searchText = data.searchText;
var definitionApi =
"https://api.dictionaryapi.dev/api/v2/entries/en/" + searchText;
var result = {
searchText: searchText,
definitions: "",
pronunciation: "",
status: "",
synonyms: "",
};
var synonyms = "";
$.ajax({
url: definitionApi,
crossDomain: true,
dataType: "json",
success: function (data) {
if (!data) return;
var content = data[0];
var phonetics = content.phonetics;
if (Array.isArray(phonetics) && phonetics.length) {
result.pronunciation = phonetics[0].text;
}
if (content && content.meanings) {
var meaningList = content.meanings;
var index = 1;
meaningList.forEach(function (meaning) {
var defs = meaning.definitions;
defs.forEach(function (definition) {
if ("synonyms" in definition) {
var synonymsArr = definition.synonyms;
if (synonymsArr) {
var syn = synonymsArr.join(", ");
synonyms +=
index +
". (" +
meaning.partOfSpeech +
") " +
syn +
"<br/>";
}
index++;
}
});
});
}
},
error: function (xhr) {
result.status = "fail";
logError(xhr.responseText);
},
}).always(function () {
result.synonyms = getSynonyms(synonyms);
callback(result);
});
}
browser.runtime.onMessage.addListener(function (data) {
setLocalStorageItem(data);
getDefinition(data, sendResponse);
});
function setLocalStorageItem(data) {
localStorage.setItem("recentSearchText", data.searchText);
}
function getSynonyms(synonyms) {
if (synonyms === "") {
return "No synonyms found";
}
return synonyms;
}
function sendResponse(result) {
var response = {
db: dictionarySettings,
search: result,
};
browser.tabs
.query({
currentWindow: true,
active: true,
})
.then(function (tabs) {
browser.tabs.sendMessage(tabs[0].id, response);
});
}
function logError(err) {
console.error(err);
}
function updateSettings(dbData) {
dbData = dbData || {};
dictionarySettings = $.extend(dictionarySettings, dbData);
}
browser.storage.onChanged.addListener(function (changes, area) {
if (area === "sync") {
browser.storage.sync.get().then(updateSettings, logError);
}
});
browser.storage.sync.get().then(updateSettings, logError);
})();