【发布时间】:2020-12-23 02:13:14
【问题描述】:
我试图在浏览 YouTube 时检测 history.popState() 事件。这是我的代码,所有这些都在我的内容脚本中:
if (window.location.href == 'https://www.youtube.com/') {
history.pushState({id: 0}, '',);
chrome.runtime.sendMessage({message: 'home'});
}
window.addEventListener('yt-navigate-start', function() {
if (window.location.href.includes('/results')) {
history.replaceState({id: 1}, '');
chrome.runtime.sendMessage({message: 'results'});
} else if ('/watch' === location.pathname) {
history.replaceState({id: 2}, '');
chrome.runtime.sendMessage({message: 'watch'});
}
});
window.addEventListener('popstate', function (event) {
setTimeout(idChange, 2000);
}, false);
if (history.state && history.state.id === 1) {
console.log('id1')
} else if (history.state && history.state.id === 2) {
console.log('id2');
} else if (history.state && history.state.id === 0) {
console.log('id0');
}
我可以在从 youtube 主页导航到结果时注册 popstate 事件事件,然后按返回按钮。但是,当我从 youtube 主页转到结果然后转到特定视频并单击返回以返回结果时,弹出状态事件不会触发。我做错了吗?
谢谢!
【问题讨论】:
-
popstate在这种情况下不会触发,因为导航是通过 pushState 执行的,这是正确的行为。我认为弄乱网站的内部历史状态不是一个好主意。有关修补 youtube 页面外观的简单示例,请参阅 this answer。
标签: javascript google-chrome google-chrome-extension youtube