I'm attempting to play a YouTube video (within an iFrame) programmatically via JS. Here is the code I'm using to programmatically play a YouTube video:
iframe.postMessage('{"event":"command","func":"playVideo","args":""}', '*');
However, in devices that support YouTube's native playback feature, the video within the iFrame becomes a black screen and doesn't open up the native video player.
How can I use the iFrame API to programmatically playback a video natively when possible?
To make an embedded video autoplay, add "&autoplay=1" to the video's embed code right after the video ID (the series of letters that follows "embed/").
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.
enablejsapi=1' to the end of the embed URL. Essentially this manager keeps track of the registered videos. If it detects that a registered video begins to play it will pause any other registered video that is currently playing.
I highly recommend you to check the Youtube Iframe Player API. https://developers.google.com/youtube/iframe_api_reference#Playback_controls
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
event.target.setVolume(100);
event.target.playVideo();
}
If you want to have the video autoplay when loaded, use this attribute in your JS: "autoplay:1". More info here: https://developers.google.com/youtube/player_parameters#autoplay
If you use the "onReady" event, you have to detect if the device allows autoplaying, which iOS does not. This is not an easy thing to test unless you use fragile UA sniffing. Using the built in method is much more reliable in this instance.
If you just want to play a video programmatically, you can use this method:
target.playVideo();
However, you again can not do this without user interaction on iOS. And it only works on iOS8, earlier versions will not allow JS to trigger the playing of videos.
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