如果播放由 postMessage 触发,则不会触发 Youtube 的 onStateChange [英] Youtube's onStateChange is not fired if play is triggered by postMessage

查看:21
本文介绍了如果播放由 postMessage 触发,则不会触发 Youtube 的 onStateChange的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果 youtube playVideo 是由 postMessage 触发的,则不会触发 onStateChange.(http://jsfiddle.net/nedvedyy/smx92nq0/).以前有人遇到过吗?

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>

奇怪的是,如果像下面这样调用 playVideo,则可以捕获 onStageChange.

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

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

推荐答案

你在这里完成作业了吗?阅读完整的手册,您的解决方案就在您粘贴的地方.

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

这篇关于如果播放由 postMessage 触发,则不会触发 Youtube 的 onStateChange的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆