3

Is there a way to display/see/return which video (so, which videoID) is playing at the moment?

This is the basic code of the Iframe API:

var player;
  function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
      height: '390',
      width: '640',
      videoId: 'pJ18QeQy0e8',
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange,
        'onError': onError,
      },
        playerVars: {

                    'controls': 0,
                    'showinfo': 0,
                    'iv_load_policy': 3,
                    'wmode': "opaque",
                },
    });
  }

after the first video has finished. This event will be called:

  function onPlayerStateChange(event) {
if(event.data === 0) {    
        player.stopVideo();
player.loadVideoById(getId());          

        }
  }

The getId() function will get another videoId to play..

I want to display in a DIV, which videoId is currently playing

Marc Ster
  • 2,276
  • 6
  • 33
  • 63

3 Answers3

20
player.getVideoData()['video_id']

OR

var video_data = player.getVideoData()
video_data['video_id']

Solution:

function onPlayerStateChange(event) {
    if(event.data === 0) {    
        player.stopVideo();
        player.loadVideoById(player.getVideoData()['video_id']);
    }
}
ByteHamster
  • 4,884
  • 9
  • 38
  • 53
cazuba
  • 329
  • 2
  • 5
4

You can use getVideoUrl to get the url and take the id part out of this url.

Ibrahim Ulukaya
  • 12,767
  • 1
  • 33
  • 36
  • 1
    Assuming that the video url is correct (watch or embed urls), you can pull the video id like so: `var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=|\?v=)([^#\&\?]*).*/; var match = e.target.getVideoUrl().match(regExp); var videoID = match[2];` – Eric Winterstine Nov 14 '17 at 16:22
0

Using window.location.href...

You can paste this into the console on desktop and if you're on a youtube video it'll take the id out of the url, not elegant at all but it works for desktop

var url = window.location.href;

var isYTvid = url.indexOf("www.youtube.com/watch?v=");
if (isYTvid != -1) {
    var id = url.slice(url.indexOf("=") + 1 , url.length);
    console.log(id);
}
Dal
  • 165
  • 10