【问题标题】:bookmarklet: getting current time of embedded iframe youtube player?小书签:获取嵌入式 iframe youtube 播放器的当前时间?
【发布时间】:2021-11-04 00:15:39
【问题描述】:

我是新手 javascript 开发人员。我有一个书签,可以获取 youtube 视频的当前时间。

javascript:(function(){
    ytplayer = document.getElementById("movie_player");
    var secs = ytplayer.getCurrentTime();
    alert(`${secs}`);
})();

它在 youtube.com 上运行良好。但是,当我将相同的逻辑应用于基于 iframe 的网站 (url here) 时。根据 youtube API 参考,我使用function onYouTubePlayerAPIReady()。但是当我运行小书签时没有任何反应。这是代码

javascript:function onYouTubePlayerAPIReady() {
   var ytplayer = new YT.Player('widget2');
   var secs = ytplayer.getCurrentTime();
   alert(`${secs}`);
}

是否有任何 youtube API 专家可以发现问题?

这是来自网站的the sample youtube的iframe

<iframe frameborder="0" allowfullscreen="1" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" title="YouTube video player" width="100%" height="100%" src="https://www.youtube.com/embed/eSWwIQzKsbY?autoplay=1&amp;mute=0&amp;controls=1&amp;start=0&amp;origin=https%3A%2F%2Fyou-tldr.com&amp;playsinline=1&amp;showinfo=0&amp;rel=0&amp;iv_load_policy=3&amp;modestbranding=1&amp;enablejsapi=1&amp;widgetid=1" id="widget2" data-gtm-yt-inspected-1_25="true"></iframe>

【问题讨论】:

    标签: javascript youtube-api bookmarklet


    【解决方案1】:

    是的。我也有类似的需求。我认为您没有调用 onYouTubeIframeAPIReady() 函数。这是工作代码。

    function onYouTubeIframeAPIReady() {
            var player = new YT.Player('widget2', {//The id of the div containing the iframe. Should be changed based on the page you're at and the i they gave their player
                events: {
                    'onStateChange': onPlayerStateChange//Event listener, fires onPlayerStateChange function whenever the state of the video changes, paused or played 
                }
            });
    
            function onPlayerStateChange() {
                currentTime = player.playerInfo.currentTime;//Current Time saved
                if (player.playerInfo.playerState === 2) {//If video paused, console.log the time
                    console.log(currentTime);
                }
            }
        }
    onYouTubeIframeAPIReady();//Initial call to the function
    

    【讨论】:

      猜你喜欢
      • 2021-08-31
      • 2020-03-11
      • 2013-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-31
      • 1970-01-01
      相关资源
      最近更新 更多