I am working on a simple page that has a text input where the user can add the id of the youtube video they want to insert into the page, then I call youtube's iframe api to load the video. However, if the user adds an id that does not exists I get a black screen.
I was hoping someone knows a way of checking if the video exists before loading it.
This is my code:
$(document).ready(function() {
$('#loadVid').click(function() {
var player;
var urlVid = $('#urlVid').val(); //GET THE VIDEO CODE FROM THE TEXT INPUT
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: urlVid,
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
});
});
Just trigger a test Ajax request to the URL before opening the player. If the Youtube page video does not exist, it returns a 404 header (I've just tested this with a non-existing video URL).
If you use the $.ajax method, you could insert the player loading function in the success callback, and trigger an error alert in the error callback (as it should be called if the response headers are 4xx or 5xx)
According to the documentation the onError should give you such info
Add the onError event handler to the events object