I have YouTube video embedded on my webpage. Can I control it by using JS?
I need to retrieve total length of the video and get events when user changes trackbar position (or position changed during playback).
I have YouTube video embedded on my webpage. Can I control it by using JS?
I need to retrieve total length of the video and get events when user changes trackbar position (or position changed during playback).
Share Improve this question edited Mar 23, 2021 at 8:00 Nakilon 35.1k16 gold badges111 silver badges147 bronze badges asked Mar 1, 2018 at 9:15 Roman PetersonRoman Peterson 914 silver badges12 bronze badges 1- 1 Have you checked libraries like video.js or plyr.js? – beaver Commented Mar 5, 2018 at 9:42
2 Answers
Reset to default 6Plyr.js
Using Plyr.js you can control YouTube (and also Vimeo) video with a simple HTML5 media player with 3 steps:
Embedding a YouTube video:
<div id="myVideo" data-type="youtube" data-video-id="4IP_E7efGWE"> </div>
Getting player instance (setup):
var videoEl = $('#myVideo').get(), player = plyr.setup(videoEl);
Handling events and using methods:
player[0].on('playing', function(event) { var instance = event.detail.plyr; console.log(" >playing"); console.log(" >duration: " + instance.getDuration()); });
Example:
here is a jsfiddle: https://jsfiddle/beaver71/2g5ggcfa/
When it es to youtube embeds the Youtube Iframe Player API will supply most of the functions needed for controlling/monitoring events from an embedded youtube video (refer to IFrame Player API Reference).
If you want to get the length of the video you can use player.getDuration()
, more details are available in the API documentation.
In regards to trackbar events the API doesn't supply a direct way to monitor those events but there is a hacky way to do it as mentioned in This question.
Another way to achieve this is by using a 3rd-party library like beaver mentioned in the ment section.
Hope this helps.