1
votes

I have a video id. And then I show a video via YouTube Player API's IFrame API. The video is displayed, and now I need to IMMEDIATELY get this video's title.

Please note that I need to IMMEDIATELY get video's title when I display a YouTube video via YouTube Player IFrame API.

What's the FASTEST way to get video title? I need the solution.

Thank you.

4

4 Answers

10
votes

It is indeed possible to get the Video Title

When calling your 'YouTube Player API's IFrame API', onready you can access the 'event.target.getVideoData().title' function:

new YT.Player('player', {
height: '390',
width: '640',
videoId: 'D3pYbbA1kfk',
events: {
  'onReady': function onPlayerReady(event) {
    alert("The video title is: " +  event.target.getVideoData().title);
  }
}
});

Full working example: https://codepen.io/anon/pen/vGOzqy?editors=0010

2
votes

It seems that it is not possible from the Player IFrame API:

https://groups.google.com/forum/?fromgroups=#!topic/youtube-api-gdata/D0w8wA0UV7A

"There's no way to get that info using the Players API. You'd need to use the Data API."

0
votes

Check the unstarted and playing state in the onStateChange event. I used this as a solution, maybe not the best but works fine.

    var info = null;
    function onStateChange(e) 
    {
        switch(e.data) {
        case YT.PlayerState.UNSTARTED:
            info = null;
            break;
        case YT.PlayerState.PLAYING:
            if(info == null)
            {
                info = {title: player.getVideoData().title, duration: player.getDuration()};
                // use info here...
            }
            break;
        }
    }
0
votes

Swift 3

You can use YTPlayerState+Extension.swift

extension YTPlayerView {
    var videoTitle: String {
        let callString = "player.getVideoData().title"
        return webView?.stringByEvaluatingJavaScript(from: callString) ?? "no title"
    }
}