javascript - 通过简单的JS强制iframe自动播放

标签 javascript html youtube-api

我有一个示例视频,它是用户将视频从 youtube 拖到轻量级 CMS 的页面 block 中的结果。视频在界面结果中显示正常,但即使从 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>

最佳答案

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

<!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>

关于javascript - 通过简单的JS强制iframe自动播放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55937651/

相关文章:

javascript - jQuery 检查输入字段字符是否突出显示

javascript - 从一个html页面点击获取链接id并将其发送到另一个页面

html - 如何在标题属性中转义双引号

php - Youtube API V3 PHP按关键字搜索代码示例不起作用

javascript - 动力学层不适用于 JavaScript 中的触摸事件

javascript - 为什么 MySQL 在闪族语言的字符串中添加单双引号

javascript - 函数 "is not defined"

javascript - 使用 JavaScript 获取选项文本/值

java - YouTubeFragmentPlayer Android 应用程序 - 仅出现黑框

php - youtube api 3.0 获取单个视频的信息