Chrome扩展在YouTube站内跳转不触发,仅刷新/直接访问生效如何解决
问题根因
YouTube属于单页应用(SPA),站内跳转是通过JavaScript修改浏览器历史记录实现的,不会触发整页刷新,所以只有页面首次加载时匹配到watch?*规则才会注入content script,站内跳转过来的场景不会触发重新注入,逻辑自然不运行。
解决方案
以下两种实现方式按需选择即可:
方案1:扩大content script注入范围+监听URL变化
改造成本最低,不需要额外加权限:
第一步:修改manifest.json的匹配规则
把content script的匹配范围扩大到整个YouTube站点,保证任意YouTube页面加载时都会注入你的脚本:
{ "manifest_version": 2, "name": "youtest", "version": "1.0.0", "content_scripts": [ { "matches": ["https://*.youtube.com/*"], "js": ["Content.js"] } ] }
第二步:修改Content.js,匹配watch页再触发逻辑
// 存储上一次的URL,避免重复触发 let lastUrl = location.href; // 核心逻辑封装 function runWatchPageLogic() { // 只在watch视频页执行 if(location.href.includes('/watch?')) { console.log(location.href); alert(location.href); } } // 首次加载时先执行一次检查 runWatchPageLogic(); // 500ms轮询检查URL变化,兼容所有SPA跳转场景,实现简单性能损耗极低 setInterval(() => { if (location.href !== lastUrl) { lastUrl = location.href; runWatchPageLogic(); } }, 500);
方案2:background脚本监听跳转事件主动注入脚本
如果不想把脚本注入到所有YouTube页面,可选择这个方案:
第一步:修改manifest.json添加权限和后台脚本
{ "manifest_version": 2, "name": "youtest", "version": "1.0.0", "permissions": ["webNavigation", "https://*.youtube.com/*"], "background": { "scripts": ["background.js"] } }
第二步:新增background.js
chrome.webNavigation.onHistoryStateUpdated.addListener((details) => { // 匹配watch视频页 if (details.url.includes('/watch?')) { // 主动注入content script chrome.tabs.executeScript(details.tabId, { file: 'Content.js' }); } }, { url: [{hostSuffix: 'youtube.com'}] });
内容的提问来源于stack exchange,提问作者emre-ozgun
相关产品推荐
相关产品推荐

