Use the YT
API and start a timer on play
, stop it on pause
or stop
. Not very accurate, since user might leave the player on yet not watching the video, but might do.
Was using YT
API long ago, but it is straight forward you hook to events as any other event in javascript and just start/stop a timer (or whatever you use to measure time). Initialy set total_viewed_time
to zero, then on play
compute a start_time
and on stop
/pause
/finish
update total_viewed_time
by the time viewed, i.e end_time-start_time
. For example see below:
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..
Additionaly if the application needs to check if user has switched browser tabs or windows, the application can listen to blur
or unfocus
event and stop the timer and re-start it on browser tab / window focus
- Is there a way to detect if a browser window is not currently active?
- Check if window has focus
- Detect If Browser Tab Has Focus