You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求JavaScript代码实现播放YouTube视频时重载页面以更新视频ID

实现方案

YouTube为单页应用(SPA),路由切换时不会触发全局页面重载,你可以根据需求二选一使用以下代码:

方案1:监听路由变化自动更新视频ID(推荐,无需重载页面)

该方案不会打断用户观看体验,监听到视频切换后直接重新拉取最新视频ID、重新渲染下载按钮即可:

// 存储上一个视频ID,避免重复触发
let lastVideoId = '';
// 监听YouTube原生导航完成事件
document.addEventListener('yt-navigate-finish', () => {
  // 从当前URL提取视频ID
  const urlParams = new URLSearchParams(window.location.search);
  const currentVideoId = urlParams.get('v');
  // 确认是视频播放页且ID发生变化
  if (currentVideoId && currentVideoId !== lastVideoId) {
    lastVideoId = currentVideoId;
    // 此处替换为你自己的下载按钮初始化/更新逻辑即可
    initYourDownloadButton(currentVideoId);
  }
});

// 首次加载页面时执行一次逻辑
window.addEventListener('load', () => {
  const urlParams = new URLSearchParams(window.location.search);
  const currentVideoId = urlParams.get('v');
  if (currentVideoId) {
    lastVideoId = currentVideoId;
    initYourDownloadButton(currentVideoId);
  }
});

方案2:切换视频时强制重载页面(满足自动重载需求)

如果你的脚本逻辑必须依赖页面重载才能运行,可以使用以下代码,监听到视频ID变化后自动重载页面:

let lastVideoId = '';
document.addEventListener('yt-navigate-finish', () => {
  const urlParams = new URLSearchParams(window.location.search);
  const currentVideoId = urlParams.get('v');
  if (currentVideoId && currentVideoId !== lastVideoId) {
    // 首次加载不重载,仅切换视频时触发重载
    if (lastVideoId !== '') {
      window.location.reload();
    }
    lastVideoId = currentVideoId;
  }
});

注意事项

  • 以上代码可以直接注入到油猴/用户脚本中运行
  • 如果是浏览器扩展脚本,需要确保代码在YouTube页面的上下文环境中执行
  • 优先使用方案1,强制重载会增加加载耗时、打断用户观看进度,体验较差

内容的提问来源于stack exchange,提问作者Aitronssesin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 15:18:03