Chrome 扩展程序未在 YouTube 的浏览器导航中加载
Posted
技术标签:
【中文标题】Chrome 扩展程序未在 YouTube 的浏览器导航中加载【英文标题】:Chrome extension is not loading on browser navigation at YouTube 【发布时间】:2013-08-26 05:13:34 【问题描述】:假设我有一个扩展程序,当您到达 YouTube 视频页面时会加载。我注意到,当您使用 Chrome 按钮来回导航时,该扩展程序很可能不会加载。
例如,我有 2 个文件,清单:
"name": "back forth",
"version": "0.1",
"manifest_version": 2,
"description": "back forth",
"permissions": ["storage", "*://www.youtube.com/watch*"],
"content_scripts": [
"matches": ["*://www.youtube.com/watch*"],
"js": ["contentscript.js"]
]
和内容脚本
alert("loaded");
来回导航时,警报并不总是出现。我该如何克服这个问题,以便每次都加载扩展程序?
【问题讨论】:
类似***.com/a/34100952/72321 【参考方案1】:YouTube 已开始试用基于 pushState 的导航。通常,只能通过注入拦截对history.replaceState
/ history.pushState
的调用的代码(或通过在后台页面中使用chrome.webNavigation.onHistoryStateUpdated
事件)在内容脚本中检测到此类导航。
此答案的其余部分特定于 YouTube。
YouTube 在加载过程中会在页面顶部显示一个(红色)进度条。此进度条使用 CSS 过渡动画。由于转换事件冒泡,您可以将转换事件侦听器绑定到<body>
,并在这些情况下检查导航。
您必须将内容脚本插入到*://www.youtube.com/*
而不是*://www.youtube.com/watch*
,因为pushState 可用于从/
导航到/watch..
。
function afterNavigate()
if ('/watch' === location.pathname)
alert('Watch page!');
(document.body || document.documentElement).addEventListener('transitionend',
function(/*TransitionEvent*/ event)
if (event.propertyName === 'width' && event.target.id === 'progress')
afterNavigate();
, true);
// After page load
afterNavigate();
注意:此方法取决于插入进度条的事实。每当 Google 决定重命名进度条的 ID 或完全删除进度条时,您的代码都将停止工作。
注意 2:这仅适用于活动标签。如果需要在tab没有聚焦的情况下检测导航变化,则需要绑定window.onfocus
和window.onblur
事件,并检查document.title
在这两个事件之间是否发生了变化。
【讨论】:
感谢您的回答。使用这种方法它可以工作,但它不像DOMContentLoaded那么早,看起来这相当于load
,有没有检测到DOMContentLoaded
-like点?
@Noitidart 如果你真的想尽快得到通知,你可以绑定到transitionstart
事件,轮询文档更改(使用setTimeout
或setInterval
)。找到所需元素后,取消注册 transitionstart 事件 + 停止轮询 + 调用自定义回调。为确保不浪费 CPU 周期,请将其与 transitionend 事件结合使用;如果您的轮询逻辑此时未检测到任何内容,请移除事件侦听器,停止轮询并调用回调。
天才的想法@RobW 谢谢!我尝试添加 window.onpopstate = function(e) console.log(e)
我认为这可以解决问题,但我没有收到任何回调。
@sports location.path
打错了,应该是location.pathname
。
@Noitidart 是的,nsIWebProgressListener
可能相当于 Firefox 中的 chrome.webNavigation.onHistoryStateUpdated
(但仅在主/后台脚本中,而不在内容脚本中,就像 Chrome 一样)。以上是关于Chrome 扩展程序未在 YouTube 的浏览器导航中加载的主要内容,如果未能解决你的问题,请参考以下文章
允许 Youtube iframe 显示与 Youtube.com 兼容的 Chrome 扩展程序
YouTube上的Chrome扩展程序和Tampermonkey [重复]