6

I am using the YouTube API in a simple one page website. I am able to get videos to play and all of my YouTube functionality works successfully in Desktop browsers (with the exception of IE 7 -- perhaps this issue will be addressed in you helping me answer this question) but it doesn't seem to work at all in iOS (iPhone and iPad.) The YouTube player simply does not show and there are no reminiscences of YouTube functionality at all in iOS.

Below is my code implementation. If there's any question information I did not provide that would be helpful for this question, please let me know. I want to start as simple as possible in addressing this issue and then bring in additional information if necessary.

/*==========================================================================
    YOUTUBE
========================================================================== */
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

var YTready = false,
    playerIdList = [],
    ytPlayers = {};

// When YouTube API is ready, switch YTready to true and run the queue of videos should any exist
// and run a list of page-specified functions such as carousel setups
var YTreadyFunctions = {};
function onYouTubeIframeAPIReady() {
    console.log('YT Ready');
    YTready = true;
    if (playerIdList.length > 0) {
        runYouTubeIframeList(playerIdList);
    }
    for(id in YTreadyFunctions){
        var thisFunc = YTreadyFunctions[id];
        var thisArgs = thisFunc.args;
        thisFunc.func(thisArgs.id,thisArgs.counters,thisArgs.isHome,thisArgs.isAutoRot,thisArgs.galleryType);
    }
}

function shortID(elemId){
    return elemId.split('-').join('');
}

function initializeYouTubeIframe(playerId,params){
        //var playerId = thisList[x];
        var thisPlayer = document.getElementById(playerId);
        ytPlayers[shortID(playerId)] = new YT.Player(playerId, {
            width: thisPlayer.getAttribute('width'),
            height: thisPlayer.getAttribute('height'),
        playerVars: {
            autohide: 1,
            //autoplay: 1,
            theme: 'light',
            showinfo: 0,
            color: 'white',
            rel: 0,
            origin: document.location.hostname,
            wmode: 'transparent'
        },
        videoId: playerId,
            events: {
                'onReady': onPlayerReady,
                'onStateChange': onPlayerStateChange
            }
        });
}

function runYouTubeIframeList(thisList) {
    // If the YouTube iFrame API (onYouTubeIframeAPIReady is not ready yet,
    // add the player(s) to a list (playerIdList) to wait until the API is ready and then initialize
    if (!YTready) {
        playerIdList.concat(thisList);
    } else {
        // YT API is ready. Initialize the list of player iframes.
        var thisListLength = thisList.length;
        for (var x = 0; x < thisListLength; x++) {
            initializeYouTubeIframe(thisList[x]);
        }
    }
}
function onPlayerReady(event) {
    //alert('player ready');
}
function onPlayerStateChange(event) {
    //alert('state changed: ' + event.data);
    if (event.data == 3) {
        $('.loading').remove();
    }
    if (event.data == 1) {
        $('#i360-static-panel').css('display','none');
        $('.loading').remove();
        $('div#i360-questions > h2').fadeIn(500).removeClass('transparent');
    }
    if (event.data == 0) {
        $('#i360-answer-mask').slideUp(function () {
            $('p.active-answer').remove();
            $('div#i360-questions > ul').fadeIn(500).removeClass('transparent');
            $('div#i360-questions > ul > li').removeClass('i360-clicked-question');
        });
        $('.i360-shown').fadeOut(300);
        $(event.target.a.parentNode).children('#i360-static-panel').css('display','block');
    }
}

// run through all yt-players and add their ID to a list of to-be-initialized players
$('.yt-player').each(function(i){
    playerIdList.push($(this).attr('id'));
});
runYouTubeIframeList(playerIdList);

function setVideoCarouselThumb(response,element){
    if(response.data){
        if(response.data.thumbnail.hqDefault){
            element.getElementsByTagName('img')[0].src = response.data.thumbnail.hqDefault;
        } else if(response.data.thumbnail.sqDefault){
            element.getElementsByTagName('img')[0].src = response.data.thumbnail.sqDefault;
        }
    } else if (response.status){
        if(response.status == '403'){
            element.setAttribute('class',element.getAttribute('class') ? element.getAttribute('class') + ' private' : 'private');
        }
    }
}
function getYouTubeInfoById(type,getID,callback,args){
    //window.console && console.log('function: getYouTubeInfoById | type = ',type,' | getId = ',getID,' | args = ',args);
    //consoleThis('https://gdata.youtube.com/feeds/api/' + type + '/' + getID + '?v=2&prettyprint=true&alt=jsonc');
    $.ajax({
        url: 'https://gdata.youtube.com/feeds/api/' + type + '/' + getID + '?v=2&prettyprint=true&alt=jsonc',
        dataType: 'jsonp',
        context: args ? args : '',
        success: function(response){
            callback(response,this);
        },
        error: function(response){
            callback(response,this);
            //consoleThis(response);
        }
    });
}

// END YOUTUBE
</script>


    <meta name="apple-mobile-web-app-title" content="Roundup" />
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="apple-mobile-web-app-title" content="Roundup" />
    <meta name="viewport" content="minimum-scale=1.0, maximum-scale=1.0">
Matt
  • 2,317
  • 7
  • 41
  • 52

1 Answers1

11

According to this other SO post, limitations exist on iOS, where "...embedded media cannot be played automatically programatically in Safari on iOS - the user always initiates playback."

I had the same problem and it turns out you can have a YouTube-API IFrame properly embedded and shown on iOS with YouTube's big red "Play" button, it's just that iOS won't let you start/stop the video with your own controls & JavaScript. E.g. you can next/previous with JavaScript, but you cannot play/pause, which has to be done by clicking on the video, then with the native controls next to the video progress bar.

But regarding the last sentence of your first paragraph and putting aside these limitations, the YouTube player should show, there is something wrong in what you did (though I'm not expert enough to tell what). I am also doing that in a simple one-page website, feel free to have a look at what I did.

Hope that helps!

Community
  • 1
  • 1
Ronan Jouchet
  • 1,303
  • 1
  • 15
  • 28
  • 3
    I'm experimenting this issue and want to register here that, if we try to AutoPlay, the video does not respond anymore. If we don't do a `playVideo()` when `onReady` everything works ok. [update] What I'm seeing is that our controls only work *after* we push the main big red button on the video. – brasofilo Oct 30 '13 at 15:29
  • I'm having the same problem. I cannot get play to work until the user presses the red play button. The "autoplay" playerVars flag doesn't work, and if I try to play the video by calling the playVideo() method, the player turns black and I can't access it anymore (there's a brief loading spinner that appears, but goes away quickly before the player goes black). – Redtopia Apr 01 '14 at 04:22
  • @Redtopia Did you fix it ? I'm having the same problem. I cannot do anything before the user clicked the red play button. But afterwards I can do load() playVideo() pauseVideo() in JS. – Elyx0 Jun 01 '14 at 21:13
  • @Elyx0, I've determined that making the user click videos to play them on mobile devices is by design. The black screen of death must be an iOS bug. (http://stackoverflow.com/questions/12496144/can-you-autoplay-html5-videos-on-the-ipad) – Redtopia Jun 02 '14 at 22:04