Search code examples
apiyoutubetrackingvideo-player

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


The twist is if someone leaves while the video is playing that same person can go back to the video page and the site will automatically play from when the user had left at.
Currently I'm using YouTube Player API to load the video.

How can I resolved this issue my friends?
I'm not sure but I'm trying to research with this key word.
But still not done.
"How to track that how much time the user spent watching on a video in YouTube Player API".


Solution

  • 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

    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