基于ChatGPT的Chrome实时自动纠错扩展开发问题求助
问题:Chrome扩展集成ChatGPT API后自动纠错功能失效并报错
我正在开发一款自用Chrome扩展,计划通过ChatGPT实现输入内容实时自动纠错——输入拼写错误单词时自动替换为正确拼写,选择ChatGPT是为了后续拓展新功能。之前实现过简单示例,但集成ChatGPT API后功能失效,目前仅在谷歌搜索栏测试,输入错误拼写无任何反应,同时持续收到以下错误:
Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
Context
https://www.autozone.com/orderConfirmation
Stack Trace
附上相关代码
manifest.json
{ "manifest_version": 3, "name": "Google Search Duplicator", "version": "1.0", "description": "Duplicates whatever is typed into the input fields.", "permissions": [ "activeTab" ], "content_scripts": [ { "matches": ["<all_urls>"], "js": ["content.js"] } ] }
content.js
// Find the Google search input element const searchInput = document.querySelector('input[name="q"]'); // Add an event listener to the search input searchInput.addEventListener('keydown', async (event) => { // Check if the pressed key is the space bar if (event.key === ' ') { // Get the current input value const currentInput = searchInput.value; // Get the last word in the input const words = currentInput.split(" "); const lastWordInput = words.length > 1 ? words.splice(-1)[0] : words[0]; // Send the last word to the Chat GPT API for autocorrection const correctedWord = await autocorrect(lastWordInput); // Add new input with corrected word const newInput = currentInput.substring(0, currentInput.lastIndexOf(" ")) + " " + correctedWord; // Update the input value with the corrected input searchInput.value = newInput; } }); // Function to send the last word to the Chat GPT API for autocorrection async function autocorrect(word) { // Send a POST request to the Chat GPT API with the word const response = await fetch('https://api.openai.com/v1/engines/davinci-codex/completions', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'KEY IS HERE' // Replace API_KEY with your actual API key }, body: JSON.stringify({ prompt: `Autocorrect the word "${word}".`, max_tokens: 1, stop: '\n' }) }); // Parse the response and return the corrected word const data = await response.json(); const correctedWord = data.choices[0].text.trim(); return correctedWord; }
问题根源及修复方案
1. 页面元素不存在导致脚本崩溃
- 你的content脚本匹配所有URL,但仅谷歌搜索页存在
input[name="q"]元素,其他页面(如autozone的订单确认页)找不到该元素,直接调用addEventListener会抛出错误,导致整个脚本终止,谷歌搜索页的功能也无法正常运行。 - 修复方式二选一:
- 缩小匹配范围:修改manifest.json的
matches字段,只针对谷歌搜索页:"matches": ["https://www.google.com/*", "https://www.google.co.uk/*"] - 增加元素存在判断:在content.js中先确认元素存在再绑定事件:
const searchInput = document.querySelector('input[name="q"]'); if (searchInput) { // 原事件监听逻辑写在这里 }
- 缩小匹配范围:修改manifest.json的
2. ChatGPT API调用错误
- 使用的
davinci-codex引擎已被弃用,且API密钥格式错误(正确格式应为Bearer 你的API密钥),同时请求参数存在问题。 - 修复:
改用gpt-3.5-turbo聊天接口(成本更低、响应更稳定),修改autocorrect函数:async function autocorrect(word) { const response = await fetch('https://api.openai.com/v1/chat/completions', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer YOUR_ACTUAL_API_KEY' }, body: JSON.stringify({ model: "gpt-3.5-turbo", messages: [ {role: "user", content: `Autocorrect the word "${word}". Return only the corrected word, no extra text.`} ], max_tokens: 10 }) }); const data = await response.json(); const correctedWord = data.choices[0].message.content.trim(); return correctedWord; }
3. 输入处理逻辑缺陷
- 当输入仅单个单词时,
currentInput.lastIndexOf(" ")返回-1,拼接后的字符串会出现开头多余空格的问题。 - 修复:调整新输入生成逻辑:
let newInput; if (words.length > 1) { newInput = words.slice(0, -1).join(" ") + " " + correctedWord; } else { newInput = correctedWord; } searchInput.value = newInput;
4. 跨域权限缺失
- Chrome扩展的content脚本发起跨域请求需要声明
host_permissions,否则请求会被浏览器拦截。 - 修复:在manifest.json中添加:
"host_permissions": [ "https://api.openai.com/*" ]
内容的提问来源于stack exchange,提问作者Russell Hertel
相关产品推荐
相关产品推荐

