2016-07-15 68 views
0

如果youtube playVideo是由postMessage触发的,则onStateChange将不会被触发。 (http://jsfiddle.net/nedvedyy/smx92nq0/)。任何人都会遇到它?如果播放是由postMessage触发的,则不会触发YouTube的onStateChange

<script src="jquery-1.10.2.min.js"></script> 
<!-- 1. The <iframe> (and video player) will replace this <div> tag. --> 
<div id="player"></div> 
<button class="button">BUTTON</button> 
<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: '390', 
      width: '640', 
      videoId: '0Bmhjf0rKe8', 
      playerVars: { 
       'controls': 1 
      }, 
      events: { 
       'onReady': onPlayerReady, 
        'onStateChange': onPlayerStateChange 
      } 
     }); 

    } 

    var playerReady = false; 
    // 4. The API will call this function when the video player is ready. 
    function onPlayerReady(event) { 
     playerReady = true; 

    } 


    // 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. 
    function onPlayerStateChange(event) { 
      alert(event); 
    } 

    $(".button").on("click", function() { 
       document.getElementById('player').contentWindow.postMessage(JSON.stringify({ 
      'event': 'command', 
      'func': 'playVideo', 
      'args': [] 
     }), "*"); 
    }); 
</script> 

奇怪的是,如果所述的playVideo被称为像以下时,onStageChange可以被捕获。

onPlayerReady=function(event) { 
    console.log("hey Im ready"); 
    event.target.playVideo(); 
} 
+0

如果你指的是'onPlayerStateChange',它的射击对我来说没有问题 – adamj

回答

-3

你在这里完成作业吗?通过完整的手册,你的解决方案就在你粘贴的地方。

https://developers.google.com/youtube/iframe_api_reference

+1

你好,请通过阅读问题您发布的任何答案之前,或者至少看看小提琴。我知道解决方案,但我问的是为什么postMessage触发playVideo不会将状态更改传递给listner – Hammer

+0

@Asharam Seervi downvoted,因为你甚至没有读过什么Hammer写的 – adamj