2013-12-10 104 views
1

我剛剛注意到,當我在本地進行測試時,Youtube事件(onReady,onStateChange)不再觸發,但在我將代碼上傳到JsFiddle時工作。我已決定複製並粘貼Youtube Player API中的代碼,我可以驗證它確實無法正常工作。有其他人有這個問題嗎? Chrome,Firefox,IE,Safari和Opera出現此問題。Youtube嵌入Iframe - 事件不在當地觸發

編輯 - 當我在我的本地console.log(player);,我看到它缺少了很多的Youtube功能,如seekTo()setVolume()showVideoInfo()這是目前在的jsfiddle。我不確定爲什麼會發生這種情況,但我相信這可能是我的問題的根源。有任何想法嗎?

http://jsfiddle.net/8ZmKx/

<!DOCTYPE html> 
<html> 
    <body> 
    <!-- 1. The <iframe> (and video player) will replace this <div> tag. --> 
    <div id="player"></div> 

    <script> 
     // 2. This code loads the IFrame Player API code asynchronously. 
     var tag = document.createElement('script'); 

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

     // 3. This function creates an <iframe> (and YouTube player) 
     // after the API code downloads. 
     var player; 
     function onYouTubeIframeAPIReady() { 
     player = new YT.Player('player', { 
      height: '190', 
      width: '140', 
      videoId: 'M7lc1UVf-VE', 
      events: { 
      'onReady': onPlayerReady, 
      'onStateChange': onPlayerStateChange 
      } 
     }); 
     } 

     // 4. The API will call this function when the video player is ready. 
     function onPlayerReady(event) { 
     console.log('ready'); 
     event.target.playVideo(); 
     } 

     // 5. The API calls this function when the player's state changes. 
     // The function indicates that when playing a video (state=1), 
     // the player should play for six seconds and then stop. 
     var done = false; 
     function onPlayerStateChange(event) { 
     console.log('change'); 
     if (event.data == YT.PlayerState.PLAYING && !done) { 
      setTimeout(stopVideo, 6000); 
      done = true; 
     } 
     } 
     function stopVideo() { 
     player.stopVideo(); 
     } 
    </script> 
    </body> 
</html> 

回答

4

看來,Youtube的IFRAME API目前壞,雖然我已經看到了沒有官方的確認。

參見:

onReady callback not firing when having the iframe explicitly written inside a template

YouTube API onPlayerReady not firing

編輯:這裏是修復:https://code.google.com/p/gdata-issues/issues/detail?id=5670#c6

下面是答案在上面的鏈接直接引:

A快速修復是添加在原始= http://www.example.com(用您的服務器替換 完整域;請確保您的網站使用http://或https:// )到iframe元素的播放器 的src =屬性。請確保origin =屬性的值 與主機域和URL方案完全匹配。例如。

<iframe 
    type="text/html" 
    width="640" 
    height="480" 
    src="https://www.youtube.com/embed/VIDEO_ID?enablejsapi=1&origin=https://www.example.com" 
    frameborder="0"> 
</iframe> 

我目前正在與工程團隊合作,以找出是否 起源=將被要求向前推進,還是這個新的 要求可以恢復,但這是立即修復。道歉 在此期間破損和缺乏先進的溝通。

如果使用YT.Player()構造函數來創建iframe元素 你那麼這不是一個問題,這是一個有點邊緣案例 開發誰被明確包括iframe元素的一部分 其頁面的HTML。

我實現了上面的修復程序,它爲我工作。

0

我已經在修復中實施了「origin =」參數,修復了原始錯誤並觸發了狀態更改事件。

現在具有原始參數導致錯誤。刪除了參數,它再次工作。