首页 > 解决方案 > Dynamic YouTube Video page - Get current Video ID & Title

问题描述

I am loading in YouTube Videos, using the iFrame API.

I have multiple div's in a layout as following :

<div id="BS3w09zFZ_Y" class="embed-responsive-item youtube-video" data-id="BS3w09zFZ_Y"></div>
<div id="Xij2kX4uumM" class="embed-responsive-item youtube-video" data-id="Xij2kX4uumM"></div>

In my JavaScript I have the following :

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

function onYouTubeIframeAPIReady()
{
    //YouTube Videos....
    $('.youtube-video').each(function(i, obj)
    {
        var video_id = $(this).data('id');
        playerInfoList.push(
                {
                    id: video_id,
                    videoId: video_id
                }
        );
    });

    for (var i = 0; i < playerInfoList.length; i++)
    {
        curplayer = createPlayer(playerInfoList[i]);
        players[i] = curplayer;
    }
}

function createPlayer(playerInfo)
{
    return new YT.Player(playerInfo.id, {
        height: playerInfo.height,
        width: playerInfo.width,
        videoId: playerInfo.videoId,
        events: {
            'onStateChange': onPlayerStateChange
        }
    });
}

// when video ends
function onPlayerStateChange(event)
{
    // var video_data = curplayer.getVideoData();
    // vid_id = video_data.video_id;
    // var video_title = video_data.title;

    console.log(curplayer.getVideoData());

    if(event.data === 0)
    {
        // Video Finished...
        // Post Via AJAX..
        $.ajax(
                {
                    type: 'POST',
                    url: '/video/mark-watched',
                    data : { _token: token, video_clip_id: vid_id, video_title: video_title, video_section: section, section_id: section_id },
                    success: function( data )
                    {
                        // Do Nothing...
                    }
                }
        )
    }
    if (event.data == YT.PlayerState.PLAYING)
    {
        // Video Playing (Left for Reference)....
    }
}

The problem I have, Is when I do the AJAX save, It is saving the last video ID in that array : Xij2kX4uumM

Is their any way I can get the current playing Video & Title?

Thanks.

标签: javascriptyoutubeyoutube-api

解决方案


推荐阅读