Chrome扩展问题:无法创建窗口并从后台脚本更新其HTML
问题根源分析
- 消息发送时机过早:后台脚本在创建标签页后立刻调用
chrome.tabs.sendMessage,但此时compilation_notification.html和关联的notification.js还未加载完成,导致接收端不存在,触发Receiving end does not exist错误。 - 内容脚本数据传递错误:你在内容脚本里错误地将
event.data赋值为"waiting",完全覆盖了注入脚本发来的真实响应数据,导致后台只能收到固定的"waiting"值。 - DOM操作错误:
notification.js里用value属性修改p标签内容,但value是输入类表单元素的专属属性,p标签应该用textContent或innerHTML。
分步解决方案
1. 修正内容脚本的数据传递错误
修改内容脚本中chrome.runtime.sendMessage的参数,正确传递注入脚本发来的output:
// 原错误代码 // chrome.runtime.sendMessage({output: event.data = "waiting"}, (response) => { // 修正后 chrome.runtime.sendMessage({output: event.data.output, type: "FROM_CONTENT"}, (response) => { console.log(response); });
2. 调整后台脚本的消息发送时机
不要在tabs.create回调里直接发消息,推荐用页面主动请求数据的方式,更可靠且避免监听事件的复杂性:
- 修改
notification.js,页面加载完成后主动向后台发送就绪消息:
// notification.js document.addEventListener('DOMContentLoaded', () => { // 向后台发送准备就绪的消息 chrome.runtime.sendMessage({type: "PAGE_READY"}, (response) => { if (response.type === "COMPILATION_DATA") { // 修改p标签内容,替换为你的目标元素ID document.getElementById('update-text').textContent = response.output; } }); });
- 后台脚本存储收到的响应数据,在收到
PAGE_READY消息时返回给页面:
// background.js let pendingOutput = null; chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) { // 处理来自内容脚本的消息 if (message.type === "FROM_CONTENT") { pendingOutput = message.output; sendResponse("msg recieved"); // 创建弹窗窗口 const targetUrl = chrome.runtime.getURL('components/compilation_notification.html'); chrome.tabs.create({url: targetUrl, active: false}, function(tab) { chrome.windows.create({ tabId: tab.id, type: 'popup', focused: true }); }); } // 处理来自页面的就绪消息 else if (message.type === "PAGE_READY") { if (pendingOutput) { sendResponse({ type: "COMPILATION_DATA", output: pendingOutput }); // 清空缓存,避免下次重复发送 pendingOutput = null; } } });
3. 修正notification.js的DOM操作错误
如果目标元素是p标签,将value改为textContent:
// 原错误代码 // document.getElementById('update-text').value = msg.output; // 修正后 document.getElementById('update-text').textContent = msg.output;
额外注意事项
- 确保
compilation_notification.html中正确引入notification.js,建议将脚本放在</body>闭合标签前,或添加defer属性,保证DOM加载完成后执行脚本。 - 检查
manifest.json中,components/compilation_notification.html和scripts/notification.js的路径配置正确,无需额外添加到web_accessible_resources(弹窗页面属于扩展内部资源)。
内容的提问来源于stack exchange,提问作者NoviceCoder
相关产品推荐
相关产品推荐

