(data: any)
| 141 | |
| 142 | // 处理翻译请求 |
| 143 | async function handleTranslationRequest(data: any): Promise<string> { |
| 144 | const { text, from, to } = data; |
| 145 | |
| 146 | if (!text || typeof text !== 'string' || text.trim() === '') { |
| 147 | return "" |
| 148 | } |
| 149 | |
| 150 | // 检查是否支持 Chrome Translation API |
| 151 | if (!isChromeTranslationSupported()) { |
| 152 | throw new Error('当前浏览器不支持 Chrome Translation API,请确保使用 Google Chrome 浏览器 v138 stable 或更高版本。'); |
| 153 | } |
| 154 | |
| 155 | // 声明变量以便在 catch 块中使用 |
| 156 | let detectedLang = from; |
| 157 | let fromLang = from; |
| 158 | let toLang = to; |
| 159 | |
| 160 | try { |
| 161 | // 检测源语言 |
| 162 | if (from === 'auto') { |
| 163 | detectedLang = await detectLanguage(text); |
| 164 | console.log('自动检测到的语言:', detectedLang); |
| 165 | } |
| 166 | |
| 167 | // 映射语言代码 - 确保使用 Chrome API 支持的格式 |
| 168 | fromLang = languageMap[detectedLang] || detectedLang; |
| 169 | toLang = languageMap[to] || to; |
| 170 | |
| 171 | console.log('语言映射:', { |
| 172 | original: { from, to }, |
| 173 | detected: detectedLang, |
| 174 | mapped: { fromLang, toLang } |
| 175 | }); |
| 176 | |
| 177 | // 如果源语言和目标语言相同,不需要翻译 |
| 178 | if (fromLang === toLang) { |
| 179 | console.log('源语言和目标语言相同,返回原文'); |
| 180 | return text; |
| 181 | } |
| 182 | |
| 183 | // 执行翻译 |
| 184 | return await performTranslation(text, fromLang, toLang); |
| 185 | |
| 186 | } catch (error) { |
| 187 | console.error('Chrome Translation API error:', error); |
| 188 | console.error('错误详情:', { |
| 189 | error: error, |
| 190 | message: error instanceof Error ? error.message : '未知错误', |
| 191 | from: from, |
| 192 | to: to, |
| 193 | detectedLang: detectedLang, |
| 194 | fromLang: fromLang, |
| 195 | toLang: toLang |
| 196 | }); |
| 197 | |
| 198 | // 提供更友好的错误信息 |
| 199 | if (error instanceof Error) { |
| 200 | if (error.message.includes('not available') || error.message.includes('not ready')) { |
no test coverage detected