最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Control embedded YouTube video by using JS - Stack Overflow

programmeradmin1浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 6

Plyr.js

Using Plyr.js you can control YouTube (and also Vimeo) video with a simple HTML5 media player with 3 steps:

  1. Embedding a YouTube video:

    <div id="myVideo" data-type="youtube" data-video-id="4IP_E7efGWE"> </div>

  2. Getting player instance (setup):

    var videoEl = $('#myVideo').get(), player = plyr.setup(videoEl);

  3. 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.

发布评论

评论列表(0)

  1. 暂无评论