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:
- Javascript random youtube video autoplay
- Random youtube video and API
- https://developers.google.com/youtube/js_api_reference?hl=de
- How do I check if a video exists on YouTube, in client side
- Youtube iframe api check if video exists
- How do I check if a video exists on YouTube, using PHP?
But most of them are outdated and simple do not answer this question.