How Can I Go To The Next YouTube Video If Current Video Is Ended With YouTube API V3 : javascript

05/02/2018


What I currently have is when the user insert a YouTube playlist URL then a iframe show up with the first video in the playlist, but after it ended it won’t go the next video.

Edit: Here is the code, it isn’t perfect. I’m still learning Promise and other JS stuff

giveUrl.addEventListener('click', getUrl);

function load() {
    knop.addEventListener('click', next);
    const ajax = function (url, type) {
        return new Promise(function (goed, fout) {
            {
                const http = new XMLHttpRequest();
                http.open('GET', url, true);
                http.onreadystatechange = function () {
                    if (http.readyState === 4 && http.status === 200) {
                        goed(this.response);
                    } else if (http.readyState === 4 && http.status !== 200) {
                        fout('Something went wrong.');
                    }
                };
                http.setRequestHeader("Accept", type);
                http.send();
            }
        });
    };
    const p = ajax(api_url, "text/json");
    p.then(
        function (data) {
            const obj = JSON.parse(data);
            let x = obj.items[y].snippet.resourceId.videoId;
            player.innerHTML = `<iframe width="640" height="390" src="https://www.youtube.com/embed/${x}?autoplay=${autoplay}" frameborder="0" ></iframe>`;
            console.log(obj);
            console.log(api_url);
        },
        function (data) {
            console.log("Mislukt: " + data);
        }
    );
    function next() {
        p.then(
            function (data) {
                const obj = JSON.parse(data);
                y++;
                let nextPage = obj.nextPageToken;
                let x = obj.items[y].snippet.resourceId.videoId;
                player.innerHTML = `<iframe width="640" height="390" src="https://www.youtube.com/embed/${x}?autoplay=${autoplay}" frameborder="0" ></iframe>`;

                if (y === obj.items.length) {
                    page_token = nextPage;
                    api_url = `https://www.googleapis.com/youtube/v3/playlistItems?&part=snippet&maxResults=50&playlistId=${playlist_id}&key=${api_key}&pageToken=${page_token}`;
                    y = 0;
                }
            }
        )
    }
}

function getUrl() {
    const url = document.getElementById('url').value;
    const myRegexp = /list=(.*)/;
    const match = myRegexp.exec(url);
    playlist_id = match[1];
    api_url = `https://www.googleapis.com/youtube/v3/playlistItems?&part=snippet&maxResults=50&playlistId=${playlist_id}&key=${api_key}&pageToken=${page_token}`;

    load();
}    

قالب وردپرس