导航栏切换页面时content.js未执行的Manifest V2插件问题求助
问题原因
目标网站是单页应用(SPA),点击导航链接时没有触发页面刷新,而是通过前端路由(比如history.pushState)更新URL和页面内容。Chrome扩展的内容脚本默认仅在页面首次加载完成时,根据matches规则注入,因此路由切换后不会自动重新注入内容脚本。另外,你内容脚本里的Console.log是大写开头,JavaScript是大小写敏感的,正确写法应该是console.log,这也是可能导致无输出的小问题。
解决方案
方法1:通过后台脚本监听URL变化,动态注入内容脚本
修改background.js,监听标签页的URL变化,当匹配目标地址时手动注入内容脚本:
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => { if (changeInfo.status === 'complete' && tab.url.includes('https://placeholder/follows')) { chrome.tabs.executeScript(tabId, { file: 'content.js' }, err => { err && console.error('注入失败:', err.message); }); } });
同时在manifest.json中添加必要权限:
{ "manifest_version": 2, "name": "Placeholder", "version": "1.1.5", "background": { "scripts": ["background.js"] }, "content_scripts": [ { "matches": ["https://placeholder/follows*"], "js": ["content.js"] } ], "permissions": ["tabs", "https://placeholder/*"] }
方法2:在内容脚本中监听路由变化
如果不想修改后台脚本,可在content.js中监听SPA的路由切换事件,重复执行逻辑:
// 首次加载时执行逻辑(修正为小写console) console.log("Hello"); // 监听浏览器前进后退事件 window.addEventListener('popstate', checkRoute); // 重写pushState/replaceState,捕获主动路由跳转 const originalPush = history.pushState; history.pushState = function(...args) { originalPush.apply(this, args); checkRoute(); }; const originalReplace = history.replaceState; history.replaceState = function(...args) { originalReplace.apply(this, args); checkRoute(); }; // 检查当前路由,匹配目标地址则执行逻辑 function checkRoute() { if (window.location.href.includes('https://placeholder/follows')) { console.log("Hello(路由切换后执行)"); // 这里放置需要重复运行的业务代码 } }
关键检查项
- 确认
matches规则中的域名完整,比如如果目标网站实际是https://placeholder.com/follows,要把规则写成"https://placeholder.com/follows*" - 内容脚本中的
console.log必须是小写开头,避免语法错误
内容的提问来源于stack exchange,提问作者HiImKobeAnd
相关产品推荐
相关产品推荐

