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":"mand","func":"playVideo","args":""}', '*');
However, in devices that support YouTube's native playback feature, the video within the iFrame bees 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?
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":"mand","func":"playVideo","args":""}', '*');
However, in devices that support YouTube's native playback feature, the video within the iFrame bees 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?
Share Improve this question asked Sep 16, 2014 at 17:28 wdewswdews 3522 silver badges18 bronze badges 1- please provide a jsfiddle. I don't believe there's a need for you to call postMessage yourself, you should use youtube's API to create the player and use the API to municate with it - it will call the postMessage internally for you. – Etai Commented Sep 23, 2014 at 18:14
2 Answers
Reset to default 6I highly remend you to check the Youtube Iframe Player API. https://developers.google./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./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.