0

I have an embedded YouTube videos in my HTML page. I'm trying to get the current time of YouTube video. I used the answer of that question to create page like this (YouTube currentTime with jQuery)

When I'm trying to display the time I'm getting an error: 'getCurrentTime is not a function'.

HTML

<div style="text-align:center"> 
  <button onclick="playPause()">Play</button> 
  <button onclick="showTime()">Show Time</button>
  <br><br>
  <iframe id = "it"  width="560" height="315" src="https://www.youtube.com/v/FHtvDA0W34I?version=3&enablejsapi=1" frameborder="0" allowfullscreen></iframe>
  <br>
  <label id=startHighlighlbl>VideoHighlightStart: </label>
</div>

JavaScript

<script> 
var tag = document.createElement('script');

tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

var player;

function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
        events: {
            'onReady': onPlayerReady
        }
    });
}

function onPlayerReady(event) {
    event.target.playVideo();
}


function ShowTime() {

    alert(player.getCurrentTime());
} 


</script>
Community
  • 1
  • 1
liorko
  • 1,435
  • 2
  • 24
  • 41

1 Answers1

-2

You should load your video through the YT-API, so player is initialized correctly and thus accessible through the API. Basically you need to remove your iframe from your HTML and instead let YT-API create the iframe for you.

Try the following:

   var tag = document.createElement('script');

   tag.src = "https://www.youtube.com/iframe_api";
   var firstScriptTag = document.getElementsByTagName('script')[0];
   firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

   var player;

   function onYouTubeIframeAPIReady() {
     player = new YT.Player('it', {
       height: '315',
       width: '560',
       videoId: 'FHtvDA0W34I',
       events: {
         'onReady': onPlayerReady,
         'onStateChange': onPlayerStateChange
       }
     });
   }

   function onPlayerReady(event) {
     event.target.playVideo();
   }

   var done = false;

   function onPlayerStateChange(event) {
     if (event.data == YT.PlayerState.PLAYING && !done) {
       setTimeout(stopVideo, 6000);
       done = true;
     }
   }

   function stopVideo() {
     player.stopVideo();
   }

   function ShowTime() {
     alert(player.getCurrentTime());
   }
<body>
  <button onclick="ShowTime()">Show Time</button>
  <br>
  <div id="it"></div>
</body
Guido Kitzing
  • 892
  • 5
  • 14
  • `Basically you need to remove your iframe from your HTML` that wasn't the issue. The **only** issue was the `id="it"` in the ` – Jaromanda X Nov 22 '15 at 13:02
  • You are correct. I saw that the wrong id a bit late. – Guido Kitzing Nov 22 '15 at 13:34