Chrome扩展开发求助:content.js注入失败及通信连接错误
Manifest V3 Chrome扩展content.js注入失败及消息通信问题解决
问题根源分析
- Manifest V3语法误用:你在
action字段内使用的executeScript是Manifest V2的写法,V3已废弃该配置,导致content.js无法被正确注入。 - Content Script未正确注册:
chrome.scripting.getRegisteredContentScripts()返回空列表,是因为你既没有通过manifest的content_scripts字段静态注册脚本,也没有调用chrome.scripting.registerContentScripts()动态注册,系统中无已注册的内容脚本记录。 - 消息发送时机错误:background service worker启动后直接调用
chrome.runtime.sendMessage(),此时content.js尚未注入目标页面,没有接收端匹配,触发"Receiving end does not exist"错误。
具体修复步骤
1. 修正manifest.json,静态注册Content Script
移除action内的executeScript配置,添加content_scripts字段实现静态注入:
{ "manifest_version": 3, "name": "Demo", "version": "0.0.0.1", "description": "demo ext", "icons": { "16": "images/icon-16.png", "32": "images/icon-32.png", "48": "images/icon-48.png", "128": "images/icon-128.png" }, "action": { "default_icon": "images/icon-32.png", "default_popup": "html/popup.html" }, "permissions": [ "declarativeNetRequest", "declarativeNetRequestFeedback", "storage", "webRequest", "contextMenus", "nativeMessaging", "scripting" ], "host_permissions": [ "*://*.example.com/*", "<all_urls>" ], "background": { "service_worker": "scripts/background.js" }, // 新增静态注册content script "content_scripts": [ { "matches": ["<all_urls>"], "js": ["scripts/content.js"] } ] }
2. 调整background.js的消息发送逻辑
避免在service worker启动时直接发送消息,改为监听页面加载完成后再发送:
// 静态注册的content script不会出现在getRegisteredContentScripts结果中,该API仅返回动态注册的脚本 // 可通过目标页面控制台查看content.js的输出验证注入状态 // 监听页面加载完成事件,确保content.js已注入 chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => { if (changeInfo.status === 'complete' && tab.url && !tab.url.startsWith('chrome://')) { chrome.tabs.sendMessage(tabId, { type: 'fetch', url: '你的目标URL', body: '请求体内容' }, response => { if (chrome.runtime.lastError) { console.error(chrome.runtime.lastError.message); return; } console.log("response:", response); }); } });
3. 修正content.js的消息回复逻辑
修复字符串拼接错误,确保返回正确的请求内容:
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){ console.log("收到消息:", request, sender); sendResponse('receive msg:' + JSON.stringify(request)); });
额外说明
- 若需仅在点击扩展图标时注入脚本,可改用动态注入方案:在popup.js中调用
chrome.scripting.executeScript(),注入完成后再发送消息:
// popup.js document.addEventListener('DOMContentLoaded', () => { chrome.tabs.query({active: true, currentWindow: true}, tabs => { chrome.scripting.executeScript({ target: {tabId: tabs[0].id}, files: ['scripts/content.js'] }).then(() => { chrome.tabs.sendMessage(tabs[0].id, {type: 'fetch', url: '', body: ''}, response => { console.log(response); }); }).catch(err => console.error(err)); }); });
内容的提问来源于stack exchange,提问作者vacuity
相关产品推荐
相关产品推荐

