【问题标题】:Forcing iframe to autoplay through simple JS通过简单的 JS 强制 iframe 自动播放
【发布时间】:2019-09-20 02:27:08
【问题描述】:

我有一个示例视频,它是用户将视频从 youtube 拖到轻量级 CMS 的页面块中的结果。视频在界面结果上显示正常,但即使从 YouTube API 中选择了自动播放,也没有自动播放。

有没有办法,可能通过 JS,我可以将页面上的任何 iframe 设置为在 youtube API 选项不起作用的情况下自动播放?

<!DOCTYPE html>
 <html>
 <head>
 </head>
 <body>
 <p><iframe src="//www.youtube.com/embed/id?start=1" width="560" height="315" frameborder="0"; autoplay; allowfullscreen="allowfullscreen"></iframe></p>
 </body>
 </html>

【问题讨论】:

    标签: javascript html youtube-api


    【解决方案1】:

    这样您就可以自动播放来自 YT 的视频

    <!DOCTYPE html>
    <html>
      <body>
        <!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
        <div id="player"></div>
    
        <script>
          // 2. This code loads the IFrame Player API code asynchronously.
          var tag = document.createElement('script');
    
          tag.src = "https://www.youtube.com/iframe_api";
          var firstScriptTag = document.getElementsByTagName('script')[0];
          firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
    
          // 3. This function creates an <iframe> (and YouTube player)
          //    after the API code downloads.
          var player;
          function onYouTubeIframeAPIReady() {
            player = new YT.Player('player', {
              height: '390',
              width: '640',
              videoId: 'p2FZvPLWf_M',
              playerVars: { 'autoplay': 1, 'controls': 1 },
              events: {
                'onReady': onPlayerReady,
                'onStateChange': onPlayerStateChange
              }
            });
          }
    
          // 4. The API will call this function when the video player is ready.
          function onPlayerReady(event) {
            event.target.playVideo();
          }
    
          // 5. The API calls this function when the player's state changes.
          //    The function indicates that when playing a video (state=1),
          //    the player should play for six seconds and then stop.
          var done = false;
          function onPlayerStateChange(event) {
            if (event.data == YT.PlayerState.PLAYING && !done) {
              //setTimeout(stopVideo, 6000);
              done = true;
            }
          }
          function stopVideo() {
            player.stopVideo();
          }
        </script>
      </body>
    </html>
    

    【讨论】:

    • 我认为这不会起作用,因为用户只是将 youtube 视频拖到页面中,所以我相信这太定制了。有没有办法只强制 iframe 播放?
    • 我想我只是想知道代码的第 3 步是否必要,因为在页面创建中已经有一个 iframe
    猜你喜欢
    • 1970-01-01
    • 2014-09-07
    • 2013-10-29
    • 1970-01-01
    • 2015-04-11
    • 2012-10-06
    • 2015-09-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多