Chrome扩展调用ChatGPT API遇TypeError:无法读取json属性
问题修复方案
核心错误原因
你代码里的fetch调用后,第一个.then((data) => console.log(data))没有返回任何值,导致下一个.then((response) => response.json())中的response是undefined,自然无法调用json()方法。
其他待修复问题
- 命令截取逻辑错误:
substr的第二个参数应为长度而非结束索引,需改用slice或计算正确长度。 - 响应解析重复:
response.json()已返回解析好的对象,无需再执行JSON.parse(data)。 - GPT-3.5-turbo响应结构错误:返回内容在
choices[0].message.content,而非choices[0].text。 - 跨域限制:Chrome扩展直接在content脚本调用OpenAI API会触发CORS,需用background脚本中转请求。
stop参数格式错误:不能直接写换行,应改为"\n"或省略该参数。
完整修正代码
1. content.js
// 提取用户输入的命令 function extractCommand(inputText) { const helpIndex = inputText.indexOf("help:"); const semicolonIndex = inputText.indexOf(";", helpIndex); if (helpIndex === -1 || semicolonIndex === -1) return ""; return inputText.slice(helpIndex + 5, semicolonIndex).trim(); } // 调用background脚本获取AI响应 function getAIResponse(command) { return new Promise((resolve, reject) => { chrome.runtime.sendMessage({ type: "fetchAI", command }, (response) => { if (response.error) reject(response.error); else resolve(response.content); }); }); } // 处理输入框内容替换 function showHelp() { const activeEl = document.activeElement; let inputText = ""; if ("value" in activeEl) { inputText = activeEl.value.trim(); } else if ("innerText" in activeEl) { inputText = activeEl.innerText.trim(); } else { console.error("不支持的输入元素类型"); return; } const command = extractCommand(inputText); if (!command) return; getAIResponse(command) .then((generatedText) => { if ("value" in activeEl) { activeEl.value = generatedText; } else if ("innerText" in activeEl) { activeEl.innerText = generatedText; } }) .catch((error) => console.error("请求失败:", error)); } // 监听输入事件 document.addEventListener("input", function (event) { const activeEl = document.activeElement; let inputText = ""; if ("value" in activeEl) { inputText = activeEl.value.trim(); } else if ("innerText" in activeEl) { inputText = activeEl.innerText.trim(); } if (inputText.endsWith(";")) { showHelp(); } });
2. background.js
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => { if (request.type === "fetchAI") { fetch("https://api.openai.com/v1/chat/completions", { method: "POST", headers: { "Content-Type": "application/json", Authorization: "Bearer YOUR_API_KEY", // 替换为你的OpenAI API密钥 }, body: JSON.stringify({ model: "gpt-3.5-turbo", messages: [{ role: "user", content: request.command }], temperature: 0.7, max_tokens: 256, n: 1, }), }) .then((response) => { if (!response.ok) throw new Error(`HTTP错误: ${response.status}`); return response.json(); }) .then((data) => { const content = data.choices[0].message.content.trim(); sendResponse({ content }); }) .catch((error) => sendResponse({ error: error.message })); return true; // 保持消息通道开放,异步返回结果 } });
3. manifest.json(确保权限配置正确)
{ "manifest_version": 3, "name": "AI输入助手", "version": "1.0", "content_scripts": [ { "matches": ["<all_urls>"], "js": ["content.js"] } ], "background": { "service_worker": "background.js" }, "permissions": ["scripting"] }
修复说明
- 将API调用移至background脚本,既避开CORS限制,也避免API密钥暴露在content脚本中。
- 修正命令截取逻辑,确保准确提取
help:和;之间的内容。 - 重构fetch调用链,移除无意义的
console.log节点,保证每个then都传递正确参数。 - 适配GPT-3.5-turbo的响应结构,正确获取返回内容。
- 通过
chrome.runtime.sendMessage实现content与background脚本的通信。
内容的提问来源于stack exchange,提问作者Prashant shekhar
相关产品推荐
相关产品推荐

