YouTube Iframe Embed

Example iframe embed highlighting issue with playback on iOS (iPad).

by ianlunn

HTML

<!-- 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: '390',
            width: '640',
            videoId: 'M7lc1UVf-VE',
            events: {
                'onReady': onPlayerReady,
                    'onStateChange': onPlayerStateChange
            }
        });
    }

    // 4. The API will call this function when the video player is ready.
    function onPlayerReady(event) {
    //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) {
        alert("state: " + event.data);
    
        if (event.data == YT.PlayerState.PLAYING && !done) {
            setTimeout(stopVideo, 6000);
            done = true;
        }
    }

    function stopVideo() {
        player.stopVideo();
    }
</script>

JavaScript

/*

Bug Report Description

This code is taken from the YouTube Player API reference (https://developers.google.com/youtube/iframe_api_reference#Getting_Started)

Start the YouTube video to have video states alerted.

The onPlayerStateChange function will alert the state numbers as they change.

The problem in the below listed browsers is that when the video starts, the unstarted (-1) and buffering (3) states are skipped. The first state shown is (1) playing.

This means, if time dependant functionality is to be executed as soon as a video is clicked, it won't happen until the video plays. As the length of buffering is different in all environments, that functionality may occur too late.

The issue has been found to occur in the following browsers:

- Chrome 29.0.1547.65 / Mac 10.8.4
- Firefox 23.0.1 / Mac 10.8.4
- Opera 16.0.1196.73 / Mac 10.8.4

The following browsers correctly show the unstarted (-1) and buffering states (3):

- Safari 6.0.5 Mac 10.8.4
- Chrome for iPad iOS6
- Safari for iPad iOS6

*/