【问题标题】:Why is Javascript Prompt only showing up when Youtube is refreshed? [duplicate]为什么只有在刷新 Youtube 时才会显示 Javascript Prompt? [复制]
【发布时间】:2022-01-04 12:20:05
【问题描述】:

我正在制作一个简单的 Chrome 扩展程序,在进入某些网站时会弹出提示。我的主要是 Youtube。这是我到目前为止的代码:

if(window.location.hostname ==="www.youtube.com") {
   let why = prompt("Why are you on Youtube/Watching this video?", "");   
   }; 

当第一次进入 youtube、刷新页面或使用返回箭头返回页面时,这可以正常工作。但是,我希望它在我单击视频或切换页面时弹出(例如,从“推荐”选项卡转到“订阅”选项卡)。我该怎么做?

编辑:我找到了适用于这个问题的代码:Detect Youtube video change with injected javascript 这是我的最终代码:

function run(){
    if(window.location.hostname ==="www.youtube.com") {
       let why = prompt("Why are you on Youtube/Watching this video?", "");
   
       };  
}
window.onload = run;
window.addEventListener('yt-navigate-start', run,   true);

【问题讨论】:

  • YouTube 很可能在观看新视频时没有刷新页面。所以这段代码不会重新运行。

标签: javascript google-chrome-extension youtube


【解决方案1】:

Youtube 是一个单页应用程序 (SPA),因此当点击视频时页面不会重新加载。你可以阅读更多关于它的信息here

您发布的代码仅在页面加载时执行,正如您已经注意到的那样,当您第一次打开 youtube 或刷新页面时会执行。

也许您可以尝试使用我从thread 获得的代码 sn-p 来收听每个视频和页面上的标题更改。

    new MutationObserver(function(mutations) {
        console.log(mutations[0].target.nodeValue);
    }).observe(
        document.querySelector('title'),
        { subtree: true, characterData: true, childList: true }
    );

【讨论】:

  • StackOverflow 还不支持链接中的#:~:text=
  • 谢谢!与此同时,我找到了正确的答案。我要更新话题了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多