【问题标题】:Youtube's onStateChange is not fired if play is triggered by postMessage如果播放由 postMessage 触发,则不会触发 Youtube 的 onStateChange
【发布时间】:2016-11-18 06:59:58
【问题描述】:

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

<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();
}

【问题讨论】:

  • 如果你指的是onPlayerStateChange,它对我来说毫无问题

标签: javascript youtube youtube-api youtube-iframe-api


【解决方案1】:

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

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

【讨论】:

  • 嗨,请在发布任何答案之前通读问题,或者至少看看小提琴。我知道解决方案,但我要问的是为什么 postMessage 触发的 playVideo 不会将状态更改传递给侦听器
  • @Asharam Seervi 投了反对票,因为你甚至没有读过 Hammer 写的内容
猜你喜欢
  • 2013-06-09
  • 2020-09-18
  • 2013-08-20
  • 1970-01-01
  • 1970-01-01
  • 2014-09-22
  • 2020-07-03
相关资源
最近更新 更多