-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathpopup.js
50 lines (44 loc) · 1.56 KB
/
popup.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
document.addEventListener('DOMContentLoaded', async () => {
const translateBtn = document.getElementById('translateBtn');
translateBtn.addEventListener('click', async () => {
try {
const lang = document.getElementById('lang').value;
// Lưu ngôn ngữ đã chọn
await chrome.storage.sync.set({ lang });
console.log('Language set to:', lang);
// Lấy tab hiện tại
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
// Đảm bảo content script đã được inject
try {
// Thử gửi message trước
const response = await chrome.tabs.sendMessage(tab.id, {
method: 'translate',
lang: lang
});
if (response?.method === 'translate') {
console.log('Translation request successful');
}
} catch (err) {
// Nếu không có content script, inject nó
if (err.message.includes('Receiving end does not exist')) {
await chrome.scripting.executeScript({
target: { tabId: tab.id },
files: ['content.js']
});
// Thử gửi message lại
const response = await chrome.tabs.sendMessage(tab.id, {
method: 'translate',
lang: lang
});
if (response?.method === 'translate') {
console.log('Translation request successful after injection');
}
} else {
throw err;
}
}
} catch (error) {
console.error('Error during translation:', error);
}
});
});