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

如何通过JS获取YouTube Shorts的标题、时长及播放进度?

YouTube Shorts 获取时长与播放进度的可行方案

方法1:直接定位Shorts的原生video元素

Shorts的播放器结构和普通YouTube视频不同,但它本质还是HTML5 video元素,直接通过选择器定位后,就能用原生的duration和currentTime属性获取数据:

// 定位Shorts的video元素(src包含shorts关键词)
const shortVideo = document.querySelector('video[src*="shorts"]');
if (shortVideo) {
  const totalDuration = shortVideo.duration; // 获取总时长
  const currentProgress = shortVideo.currentTime; // 获取当前播放进度
  console.log(`总时长:${totalDuration}s,当前进度:${currentProgress}s`);
}

方法2:实时监听播放进度变化

如果需要实时获取播放进度,可以给video元素绑定timeupdate事件:

const shortVideo = document.querySelector('video[src*="shorts"]');
if (shortVideo) {
  shortVideo.addEventListener('timeupdate', () => {
    console.log(`当前进度:${shortVideo.currentTime}s / ${shortVideo.duration}s`);
  });
}

方法3:兼容普通视频与Shorts的通用函数

可以写一个通用函数,自动适配两种视频类型,同时获取标题、时长和进度:

function getYouTubeVideoInfo() {
  // 优先尝试普通视频的播放器API
  const regularPlayer = document.getElementById('movie_player');
  if (regularPlayer && typeof regularPlayer.getVideoData === 'function') {
    return {
      title: regularPlayer.getVideoData().title,
      duration: regularPlayer.getDuration(),
      currentTime: regularPlayer.getCurrentTime()
    };
  }

  // 适配Shorts视频
  const shortVideo = document.querySelector('video[src*="shorts"]');
  if (shortVideo) {
    // 从document.title提取标题(移除末尾的" - YouTube"后缀)
    const shortTitle = document.title.replace(' - YouTube', '');
    return {
      title: shortTitle,
      duration: shortVideo.duration,
      currentTime: shortVideo.currentTime
    };
  }

  return null; // 未找到有效视频
}

// 使用示例
const videoInfo = getYouTubeVideoInfo();
if (videoInfo) {
  console.log(`标题:${videoInfo.title}`);
  console.log(`总时长:${videoInfo.duration}s`);
  console.log(`当前进度:${videoInfo.currentTime}s`);
}

注意:YouTube的页面结构可能会随时更新,如果上述选择器失效,可以通过浏览器开发者工具(F12)查看Shorts页面中video元素的最新特征,调整选择器逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 20:55:20