54 lines
1.7 KiB
JavaScript
Raw Permalink Normal View History

2026-01-17 20:24:08 +08:00
// 监听来自 content.js 的消息转发
2026-01-11 12:22:49 +08:00
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.type === "AI_TRANSLATE") {
2026-01-22 13:43:59 +08:00
// 获取 AI 配置信息和语音开关状态
2026-01-17 20:24:08 +08:00
chrome.storage.sync.get(['aiConfig', 'voiceEnabled'], async (result) => {
2026-01-11 12:22:49 +08:00
const config = result.aiConfig;
2026-01-17 20:24:08 +08:00
const voiceEnabled = result.voiceEnabled || false; // 默认为关闭
2026-01-11 12:22:49 +08:00
if (!config || !config.apiKey) {
2026-01-17 20:24:08 +08:00
sendResponse({ success: false, error: "请先在扩展图标中配置 API Key" });
2026-01-11 12:22:49 +08:00
return;
}
try {
2026-01-22 13:43:59 +08:00
// 向 AI 平台发起 fetch 请求
2026-01-11 12:22:49 +08:00
const response = await fetch(`${config.apiUrl}/chat/completions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${config.apiKey}`
},
body: JSON.stringify({
model: config.modelName,
messages: [
{ role: "system", content: request.systemPrompt },
{ role: "user", content: request.userInput }
],
temperature: 0.1
})
});
2026-01-17 20:24:08 +08:00
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error?.message || "网络请求失败");
}
2026-01-11 12:22:49 +08:00
const data = await response.json();
2026-01-17 20:24:08 +08:00
2026-01-22 13:43:59 +08:00
// 将 AI 结果和语音开关状态返回给 content.js
2026-01-17 20:24:08 +08:00
sendResponse({
success: true,
data: data,
voiceEnabled: voiceEnabled
});
2026-01-11 12:22:49 +08:00
} catch (err) {
2026-01-17 20:24:08 +08:00
console.error("AI Request Error:", err);
2026-01-11 12:22:49 +08:00
sendResponse({ success: false, error: err.message });
}
});
2026-01-17 20:24:08 +08:00
return true;
2026-01-11 12:22:49 +08:00
}
});