-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackground.js
99 lines (87 loc) · 3.34 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
// Create a context menu for saving vocabulary
chrome.contextMenus.create({
id: "saveVocab",
title: "Save Word to Flashcards",
contexts: ["selection"] // This only shows the menu when text is selected
});
// Add a listener for context menu clicks
chrome.contextMenus.onClicked.addListener((info) => {
if (info.menuItemId === "saveVocab" && info.selectionText) {
saveVocabulary(info.selectionText, "Context not provided", "Reading unavailable");
}
});
// Listen for messages from the content script and popup script
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.action === "saveVocabulary") {
saveVocabulary(message.text, "Context not provided", "Reading unavailable", message.wordInfo);
} else if (message.action === "lookupWord") {
handleWordLookup(message, sender, sendResponse);
return true; // Keep the message channel open for async response
}
});
let connectionAttempts = 0;
const MAX_RECONNECT_ATTEMPTS = 3;
// Add connection recovery
chrome.runtime.onStartup.addListener(() => {
connectionAttempts = 0;
});
async function handleWordLookup(message, sender, sendResponse) {
try {
const response = await fetch(
`https://jisho.org/api/v1/search/words?keyword=${encodeURIComponent(message.word)}`,
{
method: 'GET',
headers: {
'Accept': 'application/json',
'User-Agent': 'YomiSaver-Extension'
}
}
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
sendResponse({ success: true, data });
connectionAttempts = 0;
} catch (error) {
console.error('Proxy fetch error:', error);
if (connectionAttempts < MAX_RECONNECT_ATTEMPTS) {
connectionAttempts++;
// Retry after delay
setTimeout(() => handleWordLookup(message, sender, sendResponse), 1000);
} else {
sendResponse({ success: false, error: error.message });
}
}
}
// Update saveVocabulary function
function saveVocabulary(word, sentence, reading, wordInfo) {
console.log('Saving vocabulary:', { word, sentence, reading, wordInfo });
chrome.storage.local.get({ vocabList: [] }, (data) => {
const vocabList = data.vocabList || [];
const newEntry = {
word,
sentence: wordInfo?.sentence || sentence,
reading: wordInfo?.reading || reading,
wordInfo: {
reading: wordInfo?.reading || reading,
meanings: wordInfo?.meanings || [],
jlpt: wordInfo?.jlpt || [],
sentence: wordInfo?.sentence || sentence
},
timestamp: Date.now()
};
console.log('New entry:', newEntry);
const isDuplicate = vocabList.some(entry => entry.word === word);
if (!isDuplicate) {
vocabList.push(newEntry);
chrome.storage.local.set({ vocabList }, () => {
console.log('Vocabulary saved:', newEntry);
chrome.runtime.sendMessage({
action: 'vocabUpdated',
entry: newEntry
});
});
}
});
}