Chrome扩展问题:background.js发消息成功但content.js未执行
问题:Chrome扩展中content.js未响应background.js的消息
开发首个Chrome扩展,需要让background.js监听Netflix播放页面的重载事件,触发content.js执行DOM操作。目前已简化逻辑,仅尝试让content.js输出console.log,但无输出。background.js显示消息发送成功,却收不到content.js的日志。
相关代码
content.js
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => { if (request.action === "hello") { console.log("Hello from content script"); sendResponse({ status: "done" }); } });
background.js
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) { if (changeInfo.status === "complete" && tab.url && tab.url.includes("netflix.com/watch/")) { console.log("Netflix watch page loaded in tab", tabId); chrome.tabs.sendMessage(tabId, { action: "hello" }, () => { if (chrome.runtime.lastError) { console.error("Sending message failed:", chrome.runtime.lastError.message); } else { console.log("Message sent to content script successfully"); } }); } });
manifest.json
{ "manifest_version": 3, "name": "MyTudum", "description": "", "version": "1.0", "action": { "default_popup": "templates/popup.html", "default_icon": "images/logo.png" }, "content_scripts": [ { "js": [ "scripts/content.js" ], "matches": [ "https://*/*", "http://*/*" ], "run_at": "document_end" } ], "background": { "service_worker": "scripts/background.js" }, "icons": { "16": "images/logo.png", "32": "images/logo.png", "48": "images/logo.png", "128": "images/logo.png" }, "permissions": [ "storage", "activeTab", "scripting", "tabs" ], "host_permissions": [ "*://*.netflix.com/*" ] }
当前输出
Netflix watch page loaded in tab 317397541 Message sent to content script successfully
问题原因及修复方案
核心原因1:控制台查看位置错误
content.js运行在Netflix页面的上下文中,它的console.log会输出到当前网页的开发者控制台(按F12打开),而非扩展后台的service worker控制台。你之前可能只查看了后台控制台,因此看不到日志。
核心原因2:Netflix的单页应用特性
Netflix播放页面是单页应用(SPA),切换剧集或部分刷新操作不会触发完整的complete状态,导致chrome.tabs.onUpdated的complete事件可能不触发,或者content.js的监听未正确绑定到路由变化。
修复步骤
- 检查正确的控制台:打开Netflix播放页面的开发者控制台(F12),查看是否有
Hello from content script的日志。 - 适配SPA路由变化:修改background.js,改用
chrome.webNavigation.onHistoryStateUpdated监听页面路由变化,更适配SPA场景:
chrome.webNavigation.onHistoryStateUpdated.addListener(function(details) { if (details.url.includes("netflix.com/watch/")) { console.log("Netflix watch page route changed in tab", details.tabId); chrome.tabs.sendMessage(details.tabId, { action: "hello" }, () => { if (chrome.runtime.lastError) { console.error("Sending message failed:", chrome.runtime.lastError.message); } else { console.log("Message sent to content script successfully"); } }); } }, {url: [{hostSuffix: 'netflix.com'}]});
同时在manifest.json的permissions数组中添加"webNavigation"权限。
3. 确保content.js正确注入:打开chrome://extensions/,确认你的扩展已启用,点击扩展卡片的刷新按钮重新加载,确保content.js被正确注入到Netflix页面。
4. 调整注入时机:将content.js的run_at改为"document_idle",确保页面完全加载后再注入脚本,避免DOM未就绪导致的问题。
内容的提问来源于stack exchange,提问作者Rajveer Sodhi
相关产品推荐
相关产品推荐

