Керуємо Iframe та отримуємо інформацію відео з YouTube
YouTube allows you to embed videos through Iframes, but sometimes you need to control that video programmatically instead of poking around with controls.
You can use the api, but that's not our way of the samurai. We will manage via postMessage.
After digging through the js files of YouTube, I found quite a lot of functions that we can use.
Let's try to play the video.
Important for work, you need to add an iframe parameter to the url ?enablejsapi=1
<iframe id='video' width="560" height="315" src="https://www.youtube.com/embed/6B1zEnE3H1A?enablejsapi=1" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
To send a command to start the video, execute the command
document.querySelector('#video').contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*');
Put on pause
document.querySelector('#video').contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');
Stop the video
document.querySelector('#video').contentWindow.postMessage('{"event":"command","func":"stopVideo","args":""}', '*');
Turn off the sound
document.querySelector('#video').contentWindow.postMessage('{"event":"command","func":"mute","args":""}', '*');
Turn on the sound
document.querySelector('#video').contentWindow.postMessage('{"event":"command","func":"unMute","args":""}', '*');
The whole list of functions is there ? тут
Video information
We may not know much, but some information will be useful:
- Video title
- Author
- Link to the author's channel
- Video preview
- Html Iframe
Example
https://www.youtube.com/oembed?url=https://www.youtube.com/watch?v=6B1zEnE3H1A&format=json
{
"title": "Оnline chat site in telegram - free chat in site",
"author_name": "Oleksandr",
"author_url": "https://www.youtube.com/@PechenkiUA",
"type": "video",
"height": 113,
"width": 200,
"version": "1.0",
"provider_name": "YouTube",
"provider_url": "https://www.youtube.com/",
"thumbnail_height": 360,
"thumbnail_width": 480,
"thumbnail_url": "https://i.ytimg.com/vi/6B1zEnE3H1A/hqdefault.jpg",
"html": "<iframe width=\"200\" height=\"113\" src=\"https://www.youtube.com/embed/6B1zEnE3H1A?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen title=\"Оnline chat site in telegram - free chat in site\"></iframe>"
}
Then you can use this information at your discretion.