Getting Current YouTube Video Time

Viewed 74764

I am writing a Browser Plugin and need to find a way to get the current time a YouTube Video playing on YouTube using JavaScript. I have been playing around in the Chrome JavaScript Console and haven't had any luck.

It appears that the chrome API only works with embedded video players not a video that is playing on on youtube.com. One option I looked into is in the share section of a video their is an input box for the "start at:" time that contains the current time of the video. I have tried using .value and .text on this input box and they both return undefined? Does anyone have any ideas?

8 Answers

You can use Html5 Video API on youtube.com

var htmlVideoPlayer = document.getElementsByTagName('video')[0];
htmlVideoPlayer.currentTime

Note: It's not gonna work on Youtube Iframe API because Iframes are isolated. You cannot access the context of a Youtube IFrame .

document.querySelector('video').currentTime

Stop at specific time youtube video and show notification box in GWD

<script>
  var yid = document.getElementById("gwd-youtube_1");
  var idBox = document.getElementById("box1");
pausing_function = function(event) { 

    var aa = setInterval(function() {

        if (yid.getCurrentTime() > 8.0 && yid.getCurrentTime() < 8.1) {
            yid.pause(yid);
            idBox.style.opacity = 1;
            console.log(yid.getCurrentTime() + "playing")

             clearInterval(aa);
            yid.removeEventListener("playing", pausing_function);

        }

    }, 100)
}

 yid.addEventListener("playing", pausing_function);

  var pausing_function_1 = function() {      
       if (yid.getCurrentTime() > 8.1) {
        console.log(yid.getCurrentTime() + "pause")


        // remove the event listener after you paused the playback
        yid.removeEventListener("playing", pausing_function);
      }
    };    
  </script>

play video and hide notification

 <script type="text/javascript" gwd-events="handlers">
    window.gwd = window.gwd || {};
    gwd.pauseVideo = function(event) {
      var idBox = document.getElementById("box1");
      idBox.style.opacity = 0;
    };
  </script>
  <script type="text/javascript" gwd-events="registration">
    // Support code for event handling in Google Web Designer
     // This script block is auto-generated. Please do not edit!
    gwd.actions.events.registerEventHandlers = function(event) {
      gwd.actions.events.addHandler('gwd-youtube_1', 'playing', gwd.pauseVideo, false);
    };
    gwd.actions.events.deregisterEventHandlers = function(event) {
      gwd.actions.events.removeHandler('gwd-youtube_1', 'playing', gwd.pauseVideo, false);
    };
    document.addEventListener("DOMContentLoaded", gwd.actions.events.registerEventHandlers);
    document.addEventListener("unload", gwd.actions.events.deregisterEventHandlers);
  </script>
Related