Youtube's onStateChange is not fired if play is triggered by postMessage

时光总嘲笑我的痴心妄想 提交于 2019-12-13 02:58:16

问题


If the youtube playVideo is triggered by postMessage, the onStateChange will not be fired. (http://jsfiddle.net/nedvedyy/smx92nq0/). Any one runs into it before?

<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>

Strangely, if the playVideo is called like below, the onStageChange can be captured.

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

回答1:


Did you complete your homework here? Go through complete manual, your solution is there from where you pasted.

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



来源:https://stackoverflow.com/questions/38389802/youtubes-onstatechange-is-not-fired-if-play-is-triggered-by-postmessage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!