-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
235 lines (199 loc) · 7.22 KB
/
background.js
File metadata and controls
235 lines (199 loc) · 7.22 KB
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
// background.js - Service worker for the extension
// v2.3.0 - Robust auto-translate with retry mechanism
// Initialize default settings and create context menu
chrome.runtime.onInstalled.addListener(() => {
// Set defaults
chrome.storage.sync.set({
fromLang: 'ko',
toLang: 'en',
autoTranslate: false,
autoTranslateDomains: ['.kr']
});
// Create context menu for options (right-click on extension icon)
chrome.contextMenus.create({
id: 'translator-options',
title: 'Translator Options...',
contexts: ['action']
});
console.log('[Translator BG] Extension installed, context menu created');
});
// Ensure context menu exists on startup
chrome.runtime.onStartup.addListener(() => {
chrome.contextMenus.create({
id: 'translator-options',
title: 'Translator Options...',
contexts: ['action']
}, () => {
if (chrome.runtime.lastError) {
// Menu already exists, ignore
}
});
});
/**
* Send translate message with retry and auto-injection
* @param {number} tabId - Tab ID
* @param {string} fromLang - Source language
* @param {string} toLang - Target language
* @param {string} type - Message type ('translate' or 'autoTranslate')
* @param {number} attempt - Current attempt number
* @param {number} maxAttempts - Maximum retry attempts
*/
async function sendTranslateMessage(tabId, fromLang, toLang, type = 'translate', attempt = 1, maxAttempts = 3) {
const delays = [500, 1500, 3000]; // Increasing delays for retries
try {
const response = await chrome.tabs.sendMessage(tabId, {
type: type,
fromLang: fromLang,
toLang: toLang
});
console.log(`[Translator BG] ${type} message sent successfully to tab ${tabId}`);
return true;
} catch (error) {
console.log(`[Translator BG] Attempt ${attempt}/${maxAttempts} failed for tab ${tabId}:`, error.message);
// Try to inject content script
if (attempt === 1) {
try {
console.log(`[Translator BG] Injecting content script into tab ${tabId}`);
await chrome.scripting.executeScript({
target: { tabId: tabId },
files: ['content.js']
});
console.log(`[Translator BG] Content script injected successfully`);
} catch (injectError) {
console.log(`[Translator BG] Cannot inject content script:`, injectError.message);
// Can't inject (chrome:// page, etc.) - give up
return false;
}
}
// Retry if we have attempts left
if (attempt < maxAttempts) {
const delay = delays[attempt - 1] || 3000;
console.log(`[Translator BG] Retrying in ${delay}ms...`);
await new Promise(resolve => setTimeout(resolve, delay));
return sendTranslateMessage(tabId, fromLang, toLang, type, attempt + 1, maxAttempts);
}
console.log(`[Translator BG] All ${maxAttempts} attempts failed for tab ${tabId}`);
return false;
}
}
// Handle click on extension icon - trigger translation immediately
chrome.action.onClicked.addListener(async (tab) => {
console.log('[Translator BG] Icon clicked, triggering translation for tab:', tab.id);
const settings = await chrome.storage.sync.get(['fromLang', 'toLang']);
const fromLang = settings.fromLang || 'ko';
const toLang = settings.toLang || 'en';
await sendTranslateMessage(tab.id, fromLang, toLang, 'translate');
});
// Handle context menu click - open options popup
chrome.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId === 'translator-options') {
chrome.windows.create({
url: chrome.runtime.getURL('popup.html'),
type: 'popup',
width: 380,
height: 520
});
}
});
// Listen for messages from content script
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === 'updateIcon') {
updateIcon(sender.tab.id, message.status);
sendResponse({ success: true });
}
return true;
});
// Update extension icon based on status
function updateIcon(tabId, status) {
const iconPaths = {
gray: {
"16": "icons/icon-gray-16.png",
"48": "icons/icon-gray-48.png",
"128": "icons/icon-gray-128.png"
},
red: {
"16": "icons/icon-red-16.png",
"48": "icons/icon-red-48.png",
"128": "icons/icon-red-128.png"
},
green: {
"16": "icons/icon-green-16.png",
"48": "icons/icon-green-48.png",
"128": "icons/icon-green-128.png"
}
};
chrome.action.setIcon({
tabId: tabId,
path: iconPaths[status] || iconPaths.gray
}).catch(() => {}); // Ignore errors for closed tabs
}
// Check if a domain matches the pattern
function domainMatches(hostname, pattern) {
hostname = hostname.toLowerCase();
pattern = pattern.toLowerCase();
if (pattern.startsWith('.')) {
return hostname.endsWith(pattern) || hostname.endsWith(pattern.slice(1));
} else {
return hostname === pattern || hostname.endsWith('.' + pattern);
}
}
// Track tabs being auto-translated to prevent duplicate triggers
const autoTranslateInProgress = new Set();
// Check if page should be auto-translated
async function checkAutoTranslate(url, tabId) {
// Skip if already in progress for this tab
if (autoTranslateInProgress.has(tabId)) {
console.log('[Translator BG] Auto-translate already in progress for tab:', tabId);
return;
}
let hostname;
try {
hostname = new URL(url).hostname;
} catch (e) {
return;
}
// Skip chrome:// and other internal URLs
if (url.startsWith('chrome://') || url.startsWith('chrome-extension://') ||
url.startsWith('about:') || url.startsWith('file://')) {
return;
}
const settings = await chrome.storage.sync.get(['autoTranslate', 'autoTranslateDomains', 'fromLang', 'toLang']);
if (!settings.autoTranslate || !settings.autoTranslateDomains) {
return;
}
const shouldTranslate = settings.autoTranslateDomains.some(pattern => {
return domainMatches(hostname, pattern);
});
if (shouldTranslate) {
// Mark as in progress
autoTranslateInProgress.add(tabId);
console.log('[Translator BG] Auto-translating tab:', tabId, 'URL:', url.substring(0, 60));
// For .kr domains, always use Korean -> English regardless of page language detection
// This fixes the issue where some Korean sites don't declare their language
let fromLang = settings.fromLang || 'ko';
let toLang = settings.toLang || 'en';
// Force Korean for .kr TLD
if (hostname.endsWith('.kr')) {
fromLang = 'ko';
console.log('[Translator BG] .kr domain detected, forcing Korean source language');
}
// Wait a bit for page to stabilize, then send with retries
setTimeout(async () => {
await sendTranslateMessage(tabId, fromLang, toLang, 'autoTranslate', 1, 3);
// Clear in-progress flag after a delay
setTimeout(() => {
autoTranslateInProgress.delete(tabId);
}, 5000);
}, 1000); // Initial 1 second delay for page to load
}
}
// Listen for tab updates - auto-translate trigger
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.status === 'complete' && tab.url) {
checkAutoTranslate(tab.url, tabId);
}
});
// Clean up tracking when tab is closed
chrome.tabs.onRemoved.addListener((tabId) => {
autoTranslateInProgress.delete(tabId);
});