YouTube iFrame API: programmatically play natively?

I am trying to play a video on YouTube (in iFrame) programmatically through JS. Here is the code I use to programmatically play YouTube videos:

iframe.postMessage('{"event":"command","func":"playVideo","args":""}', '*'); 

However, on devices that support the YouTube play function, the video in the iFrame becomes a black screen and does not open its own video player.

How can I use the iFrame API to programmatically play a video whenever possible?

+5
source share
2 answers

I highly recommend you check out 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(); } 
+4
source

If you want to have the video autostart at boot, use this attribute in your JS: "autoplay: 1". More details here: https://developers.google.com/youtube/player_parameters#autoplay

If you are using the onReady event, you need to determine if the device allows autorun, which iOS is not. This is not an easy task to check if you are not using fragile UA-sniffing. Using the built-in method in this case is much more reliable.

If you just want to play the video programmatically, you can use this method:

 target.playVideo(); 

However, you again cannot do this without user interaction on iOS. And it works only on iOS8, earlier versions will not allow JS to start video playback.

+1
source

Source: https://habr.com/ru/post/1202701/


All Articles