【问题标题】:History.popState() not working with YouTube navigationHistory.popState() 不适用于 YouTube 导航
【发布时间】: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


【解决方案1】:

我遇到了类似的问题,我将我的整个 contentScript 功能封装到一个名为 ma​​in() 的函数中。

然后添加一个名为 yt-navigate-finish 的自定义事件监听器,并在每次触发此事件时调用 main()。

这样我就可以满足每次在 YouTube 上加载或导航新页面时执行 contentScript 的需要

document.addEventListener("yt-navigate-finish", function(event) {
    console.log("Content changed")
    main()
});

答案引用和修改形式https://stackoverflow.com/a/45956628/6123830

【讨论】:

    猜你喜欢
    • 2021-02-05
    • 1970-01-01
    • 2019-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多