I've been battling with the youtube iframe api for quite some time now. Somehow the method onYouTubeIframeAPIReady
is not always triggered.
From the symptoms it seems a loading problem. No errors are shown in the inspector.
Here is my code:
<div id="player"></div>
<script>
videoId = 'someVideoId';
var tag = document.createElement('script');
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
</script>
(called at the end of the page. I tried to place the code right after the above script and the result was the same.)
var isReady = false
, player
, poster
, video;
$(function () {
$('.js-play').click(function (e) {
e.preventDefault();
interval = setInterval(videoLoaded, 100);
});
});
function onYouTubeIframeAPIReady() {
console.log(videoId)
player = new YT.Player('player', {
height: '445',
width: '810',
videoId: videoId,
events: {
'onReady': onPlayerReady//,
//'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
isReady = true;
console.log("youtube says play")
}
function videoLoaded (){
if (isReady) {
console.log("ready and play")
poster.hide();
video.show();
$('body').trigger('fluidvideos');
player.playVideo();
clearInterval(interval);
}
}
The problem is that sometimes nothing gets printed by the console.log
and nothing happens.
On mobile phones this happens all the time. Any ideas?
Until and unless you have allow="autoplay;" in your iframe tag you wont be able to unmute the video. Add this attribute and further unMute function will work. Save this answer.
The IFrame player API lets you embed a YouTube video player on your website and control the player using JavaScript. Using the API's JavaScript functions, you can queue videos for playback; play, pause, or stop those videos; adjust the player volume; or retrieve information about the video being played.
Developers can use the iFrame API to programmatically create and interact with an Embed or with multiple Embeds in the same web app. The iFrame API includes methods that you can use to start playback, change the content rendering in an Embed, or stop playback.
It is not a timeout issue, and you should not need to fire this function manually.
Make sure your onYouTubeIframeAPIReady
function is available at the global level, not nested (hidden away) within another function.
You can always append it to the window object to make sure it is evoked globally. This is helpful if your code is using amd.
window.onYouTubeIframeAPIReady = function() {}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With