Chrome扩展popup.html报错:无法建立连接,接收端不存在,如何解决?
问题分析与修复方案
你遇到的Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.错误,核心原因是popup发送消息后无对应后台脚本接收,同时代码存在DOM操作、语法及配置错误,下面逐一修复:
一、后台脚本缺失消息监听(核心问题)
你的manifest.json声明了后台脚本bg.js,但该文件要么不存在,要么未监听chrome.runtime.onMessage事件,导致popup发消息时找不到接收端。
修复步骤:
创建bg.js文件,添加消息监听与OpenAI API调用逻辑:
// bg.js chrome.runtime.onMessage.addListener((request, sender, sendResponse) => { if (request.message === "clicked_browser_action") { // 调用OpenAI ChatGPT API fetch("https://api.openai.com/v1/chat/completions", { method: "POST", headers: { "Content-Type": "application/json", "Authorization": "Bearer YOUR_OPENAI_API_KEY" // 替换为你的API密钥 }, body: JSON.stringify({ model: "gpt-3.5-turbo", messages: [{role: "user", content: request.prompt}] }) }) .then(res => res.json()) .then(data => { sendResponse(data.choices[0].message.content.trim()); }) .catch(err => { sendResponse("请求出错:" + err.message); }); // 异步请求需返回true以保持响应通道 return true; } });
二、popup.js的DOM操作错误
popup.js存在两处明显错误:
- textarea的id为
input,但代码错误获取prompt元素,导致promptTextarea为null - 未正确获取textarea内容,直接使用
input变量导致undefined
修复后的popup.js:
// Popup Script const submitButton = document.getElementById("submitButton"); const clearButton = document.getElementById("clearButton"); const promptTextarea = document.getElementById("input"); // 修正元素id const responseParagraph = document.getElementById("response"); submitButton.addEventListener("click", function() { const prompt = promptTextarea.value.trim(); if (!prompt) { responseParagraph.innerText = "请输入内容"; return; } // 发送消息到后台脚本 chrome.runtime.sendMessage({ message: "clicked_browser_action", prompt: prompt }, function(response) { responseParagraph.innerText = response; }); }); clearButton.addEventListener("click", function() { promptTextarea.value = ""; responseParagraph.innerText = ""; });
三、manifest.json的MV3配置错误
Manifest V3中后台脚本需使用service_worker字段,而非script,修正后的配置:
{ "manifest_version": 3, "name": "DissBot", "description": "This is an extension that uses the ChatGPT model.", "version": "1.0", "host_permissions": [ "https://api.openai.com/" ], "action": { "default_popup": "popup.html" }, "background": { "service_worker": "bg.js" // 替换为MV3标准字段 } }
额外注意事项
- 将
bg.js中的YOUR_OPENAI_API_KEY替换为你自己的OpenAI API密钥 - 确保所有文件(popup.html、popup.js、bg.js、manifest.json)均在扩展根目录下
- 重新加载扩展:Chrome扩展页面 → 开启开发者模式 → 点击「重新加载」按钮
内容的提问来源于stack exchange,提问作者Y- turned
相关产品推荐
相关产品推荐

