// background/background.js // 监听来自 content.js 的消息转发 chrome.runtime.onMessage.addListener((request, sender, sendResponse) => { if (request.type === "AI_TRANSLATE") { // 1. 同时获取 AI 配置信息和语音开关状态 chrome.storage.sync.get(['aiConfig', 'voiceEnabled'], async (result) => { const config = result.aiConfig; const voiceEnabled = result.voiceEnabled || false; // 默认为关闭 if (!config || !config.apiKey) { sendResponse({ success: false, error: "请先在扩展图标中配置 API Key" }); return; } try { // 2. 向 AI 平台发起 fetch 请求 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 }) }); if (!response.ok) { const errorData = await response.json(); throw new Error(errorData.error?.message || "网络请求失败"); } const data = await response.json(); // 3. 将 AI 结果和语音开关状态一并返回给 content.js sendResponse({ success: true, data: data, voiceEnabled: voiceEnabled }); } catch (err) { console.error("AI Request Error:", err); sendResponse({ success: false, error: err.message }); } }); // 返回 true 表示我们将异步发送响应 return true; } });