2016-09-13 113 views
2

我使用//www.youtube.com/embed/JDcaMVwCr3c?wmode=opaque&showinfo=0&autoplay=1&controls=0&modestbranding=1&vq=&rel=0 url來在我的網站中嵌入視頻。如何恢復嵌入的YouTube視頻?

現在,如果用戶訪問該網站,則會播放視頻,但如果用戶沒有觀看完整視頻並重新加載頁面或離開網站並在一段時間後再次回來,則該視頻正在播放從一開始就。

我想從用戶離開的位置恢復視頻。就像YouTube網站一樣。

這是YouTube提供的API嗎?

回答

1

請參考下面的示例與評論。

<html> 
<head> 
</head> 
<body> 
    <div id="ytplayer"></div> 
    <script> 
     // Load the IFrame Player API code asynchronously. 
     var tag = document.createElement('script'); 
     tag.src = "https://www.youtube.com/player_api"; 
     var firstScriptTag = document.getElementsByTagName('script')[0]; 
     firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); 

     // Replace the 'ytplayer' element with an <iframe> and 
     // YouTube player after the API code downloads. 
     var player; 
     function onYouTubePlayerAPIReady() { 
      player = new YT.Player('ytplayer', { 
       height: '390', 
       width: '640', 
       videoId: 'M7lc1UVf-VE', // Youtube video ID 
       events: { 
        'onReady': onPlayerReady, 
        'onStateChange': onPlayerStateChange, 
       } 

      }); 

     } 

     function onPlayerStateChange() { 
      createCookie('ply_time', player.getCurrentTime(), 1); // Stats like buffer, Pause and play store time in Cookes 

     } 

     function onPlayerReady() { 
      player.seekTo(readCookie('ply_time')); // On ready get ccokies and start vide from that. 
     } 

     document.unload = function() {        // On docucment unload set cookie 
      createCookie('ply_time', player.getCurrentTime(), 1); 
     } 

     window.onbeforeunload = function() {    // On Window unload set cookie 
      createCookie('ply_time', player.getCurrentTime(), 1); 
     } 


     /* 
     * Start:- function to create , read and erase Cookie 
     */ 

     function createCookie(name, value, days) { 
      if (days) { 
       var date = new Date(); 
       date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); 
       var expires = "; expires=" + date.toGMTString(); 
      } 
      else 
       var expires = ""; 
      document.cookie = name + "=" + value + expires + "; path=/"; 
     } 

     function readCookie(name) { 
      var nameEQ = name + "="; 
      var ca = document.cookie.split(';'); 
      for (var i = 0; i < ca.length; i++) { 
       var c = ca[i]; 
       while (c.charAt(0) == ' ') 
        c = c.substring(1, c.length); 
       if (c.indexOf(nameEQ) == 0) 
        return c.substring(nameEQ.length, c.length); 
      } 
      return null; 
     } 

     function eraseCookie(name) { 
      createCookie(name, "", -1); 
     } 

     /* 
     * End:- function to create , read and erase Cookie 
     */ 

    </script>  
</body>