1

I am currently working on a simple website, which should run a random YouTube video inside an iframe (vid):

<script>
        function makeid(length)
        {
            var text = "";
            var possible = "0123456789-_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

            for( var i=0; i < length; i++ )
                text += possible.charAt(Math.floor(Math.random() * possible.length));

            return text;
        }

        function validateYouTubeUrl(myID)
        {
            var videoID = myID;

            var request = new XMLHttpRequest;
            request.open('GET', 'http://www.youtube.com/v/'+videoID, true);
            request.send();
            request.onreadystatechange = function(){
                if(request.status==200){
                    return false;
                }else{
                    return true;
                }
            }
        }

        // Load a random video (by setting the source of the iframe)
        function getRandom() {
            vidId=makeid(11); // Create an ID
            while(validateYouTubeUrl(vidId)){ // If the ID is not valid,...
                vidId=makeid(11); // ... than create a new one and validate it again
            }

            document.getElementById("vid").src="http://www.youtube.com/embed/"+vidId;
        }
</script>

The problem is CORSE and the missing YouTube API. I know of the following links:

But most of them are outdated and simple do not answer this question.

Community
  • 1
  • 1
TheRealVira
  • 1,444
  • 4
  • 16
  • 28

1 Answers1

2

try with https://www.googleapis.com/youtube/v3/videos.

function validateYouTubeUrl(myID)
    {
        var videoID = myID;

        var request = new XMLHttpRequest();
        request.open('GET', 'https://www.googleapis.com/youtube/v3/videos?id='+ videoID + '&key=KEY&part=snippet', true);
        request.send();

        if (request.status === 200) {
        var response = JSON.Parse(request.responseText);
            if (response.pageInfo.totalResults == 0) {
                 return false;
            } else {
                 return true;
            }
        } else {
            return false;
        }
        temp.pageInfo.totalResults
    }
Cth103
  • 63
  • 5