-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtranslator.js
More file actions
265 lines (220 loc) · 8.91 KB
/
translator.js
File metadata and controls
265 lines (220 loc) · 8.91 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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
document.addEventListener('DOMContentLoaded', function() {
const sourceText = document.getElementById('sourceText');
const translatedText = document.getElementById('translatedText');
const targetLang = document.getElementById('targetLang');
const langSearch = document.getElementById('langSearch');
const speakerButton = document.getElementById('speakerButton');
const sourceSpeakerButton = document.getElementById('sourceSpeakerButton');
const copyButton = document.getElementById('copyButton');
const sourceCopyButton = document.getElementById('sourceCopyButton');
let translateTimeout;
let speechUtterance = null;
let isSpeaking = false;
let isSourceSpeaking = false;
// 建立与后台脚本的长连接
const port = chrome.runtime.connect({name: 'sidePanel'});
// 通知后台脚本侧边栏已准备就绪
port.postMessage({action: 'ready'});
// 初始化语言选项
function initializeLanguageOptions() {
const sortedLanguages = Object.entries(SUPPORTED_LANGUAGES)
.sort((a, b) => a[1].localeCompare(b[1], 'zh-CN'));
targetLang.innerHTML = sortedLanguages
.map(([code, name]) => `<option value="${code}">${name}</option>`)
.join('');
// 从 storage 中读取上次使用的语言
chrome.storage.local.get(['lastUsedLanguage'], function(result) {
if (result.lastUsedLanguage) {
targetLang.value = result.lastUsedLanguage;
}
});
}
// 搜索语言
function filterLanguages(searchText) {
const currentValue = targetLang.value;
const sortedLanguages = Object.entries(SUPPORTED_LANGUAGES)
.filter(([code, name]) =>
name.toLowerCase().includes(searchText.toLowerCase()) ||
code.toLowerCase().includes(searchText.toLowerCase()))
.sort((a, b) => a[1].localeCompare(b[1], 'zh-CN'));
targetLang.innerHTML = sortedLanguages
.map(([code, name]) => `<option value="${code}">${name}</option>`)
.join('');
// 如果之前的值在过滤后的结果中存在,则保持选中
if (sortedLanguages.some(([code]) => code === currentValue)) {
targetLang.value = currentValue;
} else if (sortedLanguages.length > 0) {
// 如果之前的值不存在,选择第一个选项并触发翻译
targetLang.value = sortedLanguages[0][0];
// 保存选择的语言
chrome.storage.local.set({ 'lastUsedLanguage': targetLang.value });
// 如果有文本,则触发翻译
if (sourceText.value) {
translateText();
}
}
}
// 初始化语言列表
initializeLanguageOptions();
// 添加语言搜索事件监听
langSearch.addEventListener('input', (e) => {
filterLanguages(e.target.value);
});
async function translateText() {
const text = sourceText.value;
const target = targetLang.value;
if (!text) {
translatedText.value = '';
return;
}
try {
const url = `https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=${target}&dt=t&q=${encodeURIComponent(text)}`;
const response = await fetch(url);
const data = await response.json();
let result = '';
data[0].forEach(item => {
if (item[0]) {
result += item[0];
}
});
translatedText.value = result;
speakerButton.disabled = false; // 启用播放按钮
} catch (error) {
translatedText.value = '翻译出错,请稍后重试';
speakerButton.disabled = true; // 禁用播放按钮
console.error('Translation error:', error);
}
}
// 监听输入事件,使用防抖处理
sourceText.addEventListener('input', function() {
clearTimeout(translateTimeout);
translateTimeout = setTimeout(translateText, 500); // 改为0.5秒后执行翻译
});
// 监听语言选择变化
targetLang.addEventListener('change', function() {
// 保存选择的语言
chrome.storage.local.set({ 'lastUsedLanguage': targetLang.value });
// 如果输入框有内容,立即触发翻译
if (sourceText.value) {
translateText();
}
});
// 播放翻译后的文本
function playTranslatedText() {
if (isSpeaking) {
window.speechSynthesis.cancel();
isSpeaking = false;
speakerButton.classList.remove('playing');
return;
}
const text = translatedText.value;
if (!text) return;
speechUtterance = new SpeechSynthesisUtterance(text);
speechUtterance.lang = targetLang.value;
speechUtterance.onend = function() {
isSpeaking = false;
speakerButton.classList.remove('playing');
};
speechUtterance.onerror = function() {
isSpeaking = false;
speakerButton.classList.remove('playing');
};
window.speechSynthesis.speak(speechUtterance);
isSpeaking = true;
speakerButton.classList.add('playing');
}
// 添加播放按钮点击事件
speakerButton.addEventListener('click', playTranslatedText);
// 复制翻译结果
async function copyTranslatedText() {
const text = translatedText.value;
if (!text) return;
try {
await navigator.clipboard.writeText(text);
} catch (err) {
console.error('复制失败:', err);
}
}
// 添加鼠标按下和松开事件
copyButton.addEventListener('mousedown', () => {
copyButton.classList.add('copied');
});
copyButton.addEventListener('mouseup', () => {
copyButton.classList.remove('copied');
copyTranslatedText();
});
// 鼠标移出按钮时也要移除样式
copyButton.addEventListener('mouseleave', () => {
copyButton.classList.remove('copied');
});
// 复制原文
async function copySourceText() {
const text = sourceText.value;
if (!text) return;
try {
await navigator.clipboard.writeText(text);
} catch (err) {
console.error('复制失败:', err);
}
}
// 播放原文
function playSourceText() {
if (isSourceSpeaking) {
window.speechSynthesis.cancel();
isSourceSpeaking = false;
sourceSpeakerButton.classList.remove('playing');
return;
}
const text = sourceText.value;
if (!text) return;
const utterance = new SpeechSynthesisUtterance(text);
// 从翻译 API 的响应中获取源语言
fetch(`https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=${targetLang.value}&dt=t&q=${encodeURIComponent(text)}`)
.then(response => response.json())
.then(data => {
// 获取检测到的源语言
const detectedLanguage = data[2];
utterance.lang = detectedLanguage;
utterance.onend = function() {
isSourceSpeaking = false;
sourceSpeakerButton.classList.remove('playing');
};
utterance.onerror = function() {
isSourceSpeaking = false;
sourceSpeakerButton.classList.remove('playing');
};
window.speechSynthesis.speak(utterance);
isSourceSpeaking = true;
sourceSpeakerButton.classList.add('playing');
})
.catch(error => {
console.error('语言检测失败:', error);
// 如果检测失败,仍然尝试播放
window.speechSynthesis.speak(utterance);
isSourceSpeaking = true;
sourceSpeakerButton.classList.add('playing');
});
}
// 添加原文复制按钮事件
sourceCopyButton.addEventListener('mousedown', () => {
sourceCopyButton.classList.add('copied');
});
sourceCopyButton.addEventListener('mouseup', () => {
sourceCopyButton.classList.remove('copied');
copySourceText();
});
sourceCopyButton.addEventListener('mouseleave', () => {
sourceCopyButton.classList.remove('copied');
});
// 添加原文播放按钮事件
sourceSpeakerButton.addEventListener('click', playSourceText);
// 监听来自后台的消息
port.onMessage.addListener((msg) => {
if (msg.action === "translateText") {
sourceText.value = msg.text;
// 触发翻译
clearTimeout(translateTimeout);
translateTimeout = setTimeout(translateText, 500);
}
});
});