【问题标题】:getting current time of youtube videos while playing在播放时获取 youtube 视频的当前时间
【发布时间】:2018-11-03 20:47:17
【问题描述】:

当我播放这样的 Youtube 视频时:

https://www.youtube.com/tv?#/watch/video/control?v=d1-VK12FZhs&resume&t=0m4s

我在视频底部看到了播放时间和持续时间。

我可以知道当前播放时间在页面中查找:

0:11

一段时间后,此信息将被隐藏,直到我再次将鼠标指针移到视频上。

显示信息时,我可以每秒更新 ytp-time-current 值。 隐藏信息时,不会更新此值。 信息隐藏时如何获取当前时间?

我在带有此代码的 chrome 扩展中使用它:

document.addEventListener("spfdone", process); 
document.addEventListener("DOMContentLoaded", process); 

function process(){ 
stop(); 
start(); 
} 
window.onbeforeunload = function () { 
stop(); 
}; 

function start(){ 

x2 = setInterval(function() { 

// here is the place to use the solution i'm looking for

},1000); 
} 

function stop(){ 
}

提前致谢。

【问题讨论】:

  • 您如何使用该视频?你将它嵌入到 iframe 中还是...?
  • 我直接在chrome浏览器中播放
  • 那么,您正在寻找一种使用 javascript 在控制台中获取时间的方法吗?
  • 是的。这就是我需要的
  • 我修改了 youtube 视频的 url,因为我使用的是 tv 格式。抱歉这么晚的改动。

标签: javascript html youtube


【解决方案1】:

根据 YouTube iframe api,您可以使用:getCurrentTime()

在chrome控制台中写下如下代码即可:

document.querySelector('.video-stream').getCurrentTime()

【讨论】:

  • 我收到此错误:未捕获的 TypeError:document.querySelector(...).getCurrentTime 不是函数
  • 代码需要跑进页面,而不是ext。因此,将该代码注入页面并使用事件传回值...
  • 可以在分机中以任何方式使用吗?我需要在 ext 上使用
【解决方案2】:

这是您要显示的内容的完整解决方案:

var player = document.getElementById('movie_player');
var time = player.getCurrentTime();
var sec_num = parseInt(time, 10);
var hours   = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
if (hours < 10)
   hours = '0' + hours;
if (minutes < 10)
   minutes = '0' + minutes;
if (seconds < 10)
   seconds = '0' + seconds;
alert(hours + ':' + minutes + ':' + seconds);

【讨论】:

  • 我收到此错误:未捕获的 TypeError:player.getCurrentTime 不是函数
  • 你是如何运行代码的?你说你想在 JS 控制台中获取当前时间!我刚刚使用 FireFox 和 Chrome 控制台对其进行了测试,并且都显示了当前时间的警报
  • 我在 chrome 扩展中使用代码。我想如果这适用于控制台应该也适用于扩展......
  • 我明白了,chrome 扩展会在页面准备好之前初始化,你能在几秒钟后用 setTimeout 再次测试
  • 抱歉,我不明白我需要做什么?目前我每秒都在打电话。我认为一段时间后必须加载页面......
猜你喜欢
  • 2011-10-21
  • 1970-01-01
  • 2020-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-27
  • 2011-05-20
  • 2020-06-27
相关资源
最近更新 更多