Why YouTube JavaScript Player API open a different URL than the one in my code, and just play the first video of a playlist?

不想你离开。 提交于 2019-12-01 14:55:10

I finally found an alternative way to make it work with an iframe.

Here is the code :

<div id="player"></div>

<script>

  var tag = document.createElement('script');

  tag.src = "https://www.youtube.com/iframe_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

  var player;
  function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
      height: '100%',
      width: '100%',
      events: {
        'onReady': onPlayerReady
      }

    });
  }

  function onPlayerReady(event) {

    event.target.loadPlaylist({'listType': 'playlist',
                               'list': 'PLo-QIlIZx6myBxEysxrWoE-f58-psKGji',
                               'index': '0'
                              });
      event.target.mute();
      event.target.setLoop(true);
    setTimeout( function() { 
        event.target.setShuffle(true); 
    }, 2000);
      }
</script>

Thank you for the help :-)

...the player doesn't detect my playlist and just play the first video.

Youtube has moved on to the newer iFrame API and that one does allow playlists.

Try this example code below by pasting it here (click "See Result")

<!DOCTYPE html>
<html>
<body>

<iframe width="700" height="400"
src="https://www.youtube.com/embed/HuIGf4IJzdM?list=PLo-QIlIZx6myBxEysxrWoE-f58-psKGji">
</iframe>

</body>
</html>

See how it's within an <iframe> tag? Not SWF, not JS, just working with iFrame. You must add a similar tag to your website code (remove & replace your shown script code).

NOTES :

  • Also notice the iFrame url begins with https://www.youtube.com/embed/ this gives you the HTML5 player meaning it will work on mobile too. Site visitors using phones or tablets can watch. This is the best working option for all your site visitors.
  • If you really want Flash in the iFrame then change beginning to https://www.youtube.com/v/ this gives you the SWF player which means it will need the Flash Player plugin (not available on mobile). People using phones or tablets to visit your site cannot watch (they get a blank white box or some message like "Plugin not available").
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!