如何跟踪用户在 YouTube 播放器中观看视频所花费的时间 API

How to track that how much time the user spent watching on a video in YouTube Player API

不同之处在于,如果有人在播放视频时离开,同一个人可以返回视频页面,网站会自动从用户离开时开始播放。
目前我正在使用 YouTube 播放器 API 加载视频。

朋友们,我该如何解决这个问题?
我不确定,但我正在尝试用这个关键词进行研究。
但还是没有完成。
"How to track that how much time the user spent watching on a video in YouTube Player API".

使用 YT API 并在 play 上启动计时器,在 pausestop 上停止计时器。不太准确,因为用户可能会打开播放器但不观看视频,但也可能会这样做。

很久以前就在使用 YT API,但是您可以像 javascript 中的任何其他事件一样直接挂钩事件,而只是 start/stop 一个计时器(或无论你用什么来衡量时间)。最初将 total_viewed_time 设置为零,然后在 play 上计算 start_time 并在 stop/pause/finish 上更新 total_viewed_time查看的时间,即 end_time-start_time。例如见下:

var total_viewed_time = 0, start_time = 0, end_time = 0;

// assume we have a yt video which we we hook for events (see YT API for exactly how to hook)
ytvideo.on('play', function( ){
    start_time = new Date().getTime(); // milliseconds
    end_time = start_time;
});
ytvideo.on('pause stop finish', function( ){
   end_time = new Date().getTime(); // milliseconds
   total_viewed_time += end_time-start_time; // milliseconds
});

// total_viewed_time measures how much time (in milliseconds) the user had the player on (maybe watching?)
// you can then convert this time to seconds or minutes or whatever suits you
// to get the time in seconds do: total_viewed_time/1000
// to get the time in minutes do: total_viewed_time/(60*1000)
// and so on..

此外如果应用程序需要检查用户是否切换了浏览器标签或windows,应用程序可以监听blurunfocus 事件并停止计时器并在浏览器选项卡上重新启动它 / window focus

  1. Is there a way to detect if a browser window is not currently active?
  2. Check if window has focus
  3. Detect If Browser Tab Has Focus