-
Notifications
You must be signed in to change notification settings - Fork 0
/
background.js
151 lines (135 loc) · 4.1 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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
let selectedVoice;
chrome.runtime.onInstalled.addListener(function() {
chrome.contextMenus.create({
id: "parent",
title: "BrowseWise",
contexts: ["selection"]
});
chrome.contextMenus.create({
id: "add_note",
parentId: "parent",
title: "Add to Note",
contexts: ["selection"]
});
chrome.contextMenus.create({
id: "speak",
parentId: "parent",
title: "Speak Text",
contexts: ["selection"]
});
chrome.contextMenus.create({
id: "definition",
parentId: "parent",
title: "Definition",
contexts: ["selection"]
});
chrome.contextMenus.create({
id: "highlight",
parentId: "parent",
title: "Highlight Text",
contexts: ["selection"]
});
});
// handling all context menus
//1.
chrome.contextMenus.onClicked.addListener(function(info, tab) {
if (info.menuItemId === "speak") {
if (selectedVoice) {
chrome.tts.speak(info.selectionText, { "voiceName": selectedVoice.voiceName, 'lang': selectedVoice.lang, 'rate': 1.0 });
} else {
chrome.tts.speak(info.selectionText, { 'rate': 1.0 });
}
}
//2.
else if (info.menuItemId === "definition") {
getDefinition(info.selectionText, async(definition)=>{
await chrome.notifications.create({ //to display as chrome notification
type: 'basic',
iconUrl: 'icon.png',
title: 'Definition',
message: definition
});
});
}
//3.
else if (info.menuItemId === "highlight") {
chrome.scripting.executeScript({ //to inject js or css to the target context
target: { tabId: tab.id },
function: highlightSelectedText
});
}
//4.
else if (info.menuItemId === "add_note") {
chrome.scripting.executeScript({ //the syntax is injection , callback
target: { tabId: tab.id },
function: copyToClipboard,
args: [info.selectionText]
}, () => {
chrome.scripting.executeScript({
target: { tabId: tab.id },
function: openNotePopup,
args: [info.selectionText]
});
});
}
});
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
if (message.type === 'SET_SELECTED_VOICE') {
selectedVoice = JSON.parse(message.voice); //parse method is used to make a js object
console.log('Received selected voice in background script:', selectedVoice);
}
else if (message.type === 'SAVE_NOTE') {
chrome.storage.local.get('notes', function(data) {
const notes = data.notes || [];
notes.push({ heading: message.heading, content: message.content });
chrome.storage.local.set({ notes }, function() {
sendResponse({ status: 'saved' });
});
});
return true;
}
});
function getDefinition(word, callback) {
const url = `https://api.dictionaryapi.dev/api/v2/entries/en/${word}`;
fetch(url)
.then(response => response.json())
.then(data => {
if (data && data.length > 0 && data[0].meanings && data[0].meanings.length > 0) {
const definition = data[0].meanings[0].definitions[0].definition;
callback(definition);
} else {
callback("No definition found");
}
})
.catch(err => {
console.error(err);
callback("Error fetching definition");
});
}
function highlightSelectedText() {
const selection = window.getSelection();
if (selection.rangeCount > 0) {
const range = selection.getRangeAt(0);
const span = document.createElement('span');
span.style.backgroundColor = 'yellow';
span.style.color = 'black';
span.appendChild(range.extractContents());
range.insertNode(span);
}
}
function openNotePopup() {
const noteContent = window.prompt('Enter note content:' , "Press ctrl+V to paste selected text");
const noteHeading = window.prompt('Enter note heading:');
if (noteHeading && noteContent) {
chrome.runtime.sendMessage({ type: 'SAVE_NOTE', heading: noteHeading, content: noteContent });
}
}
async function copyToClipboard(text, callback) {
try{
await navigator.clipboard.writeText(text).then(callback).catch(err => {
console.error('Failed to copy text: ', err);
});
}catch(error){
console.error(error)
}
}