Youtube iframe api check if video exists - javascript

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
}
});
});
});

According to the documentation the onError should give you such info
100 – The video requested was not found. This error occurs when a
video has been removed (for any reason) or has been marked as private.
Add the onError event handler to the events object
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange,
'onError': function(errEvent) {
var errCode = errEvent.data;
if(errCode == 100) {
alert('Video Not Found');
}
}
}

Here $videoId contain video id of yuotube url
public function checkVideoExists() {
$headers = get_headers('http://gdata.youtube.com/feeds/api/videos/' . $videoId);
if (!strpos($headers[0], '200')) {
echo "The YouTube video you entered does not exist";
return false;
}
}

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)

Related

Youtube video API onStateChange event cannot be used to change video

I want to use the onStateChange event provided by the Youtube API to listen to for the end of the video and then get a new video to play in the player. However, this does not seem to be possible for some reason.
function onPlayerStateChange(event) {
if(event.data === 0) {
console.log('done');
goNext();
}
}
function goNext() {
player.loadVideoById('JBJ1VPBrCl0', 0, 'default');
}
I register the event handler like this
player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
height: '530',
width: '640',
videoId: '0Bmhjf0rKe8',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
Problem is: if I call my function goNext() manually, the video changes. If I wait for the video termination, the 'done' message is printed to the console, but the video does not change. Any ideas what am I doing wrong?
I've put up a fiddle here. Thanks!
http://jsfiddle.net/PHXY2/
FWIW, your fiddle example worked fine for me (after the video ends it automatically starts playing the "Short - Cat Meowing - Funny Cat Video - Red Laser" video ) Did you happen to have any YouTube-related browser extensions installed earlier? Some have been known to cause issues with the YT API.

Check if Embedded YouTube Video has Finished

So I'm writing a TamperMonkey script that sends specific videos to YouTube's embedded player however I want to automatically send them back once the video is finished.
So for example, video http://youtube.com/watch?v=XXXXX it would redirect to http://youtube.com/v/XXXXX. And then, once the video is complete, it would use window.history.go(-2) (as -1 would go to the normal page causing a loop).
The problem I'm having is that I haven't been able to get the second part, the function that runs when the video finishes, to work.
I have tried following the api and looking at other peoples problems and seeing what helped them but I can't seem to get it.
At the moment this is the code I have.
$(document).ready( function() {
var loc = document.location.href;
var l = loc.split('/');
var s = l[4];
var id = s.split('?')[0]
// create youtube player
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
height: '100%',
width: '100%',
videoId: id,
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// autoplay video
function onPlayerReady(event) {
event.target.playVideo();
alert('spotted');
}
// when video ends
function onPlayerStateChange(event) {
if(event.data === 0) {
window.history.go(-2);
}
}
});
I would appreciate it if someone would work with me to get this script working.
Thanks.

Youtube API - not loading if the user in not in the tab (FireFox)

I´ve been messing around with the youtube API for a while now.
I´m currently making a website where users can create custom playlists from different sources (youtube, soundcloud,...).
After one video is finished it checks on the go to the url with the next video.
The problem is that when you are in another tab than the one where the video plays and the next video loads, the API won´t load.
The only way to avoid this is by opening the link in a own browser.
(I use firefox btw)
It works with Internet Explorer though!
For the html part: I use the standard Iframe code
API:
<script>
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: '<?php echo $link; ?>',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
}
function onPlayerReady(event) {
event.target.playVideo();
}
function onPlayerStateChange(event) {
console.log('State is:', >event.data);
if(event.data === 0) {
window.location="link";
}
}

Youtube IFrame api getVideoLoadedFraction() not called in iOS

I read links about YouTube IFrame API and doing a sample which has iFrame in HTML.
I need the below function to be called:
player.getVideoLoadedFraction();
I am using the below code for creating player object.
var player;
function onYouTubeIframeAPIReady()
{
alert('onYouTubeIframeAPIReady');
player = new YT.Player('player', {
height: '432',
width: '768',
videoId: 'tNpd9LCaG8',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
alert('player created');
}
and for testing purpose I added the player.getVideoLoadedFraction() in the onStateChange event.
function onPlayerStateChange(event)
{
alert("onStateChange has fired!\nNew state:" + event.data);
var progress = player.getVideoLoadedFraction();
alert (progress);
}
this method is not getting called. Even if I put any alert after var progress = player.getVideoLoadedFraction(); this line, alert is not displaying.
Can anyone help me to solve this.
Thank you
Don't call player.getVideoLoadedFraction(), call event.target.getVideoLoadedFraction().

Youtube API calling player functions after player is initated

This is my first use of the youtube api and I'm finding it hard understanding the documentation. Basically I have multiple videos on the page, when you click one it pops up in a lightbox and plays the correct video. All of this works fine.
The client now wants all the videos to be automatically muted on start, and once you finish the video they want the frame to skip to the right place.
If I use the youtube iframe api i can't seem to be able to update the videoId at all. Below is my code:
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
height: '323',
width: '576',
videoId: 'Fy7Li0dMRSY',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
event.target.mute(); // this does not do anything
event.target.playVideo();
}
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
//setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
function loadVid(vidID, title){
// loads youtube video with video title & youtube video ID
$('.lightbox .title').html(title);
$('.lightbox iframe').prop('src','https://www.youtube.com/embed/'+vidID+'?rel=0&wmode=transparent&enablejsapi=1');
//player.mute() does not work here
showLightbox();
}
My problem is trying to call the player function to mute inside the loadVid function, it throws back an error (any function throws the same error) and I can't figure out how to use functions such as player.
The error is player.stopVideo is not a function
So how can I mute the video on start? Adding it to onPlayerReady does not work either.
Move the event.target.mute(); to the onPlayerStateChange function like this:
var done = false;
function onPlayerStateChange(event) {
event.target.mute();
if (event.data == YT.PlayerState.PLAYING && !done) {
//setTimeout(stopVideo, 6000);
done = true;
}
}
When you have multiple videos on the page, you still have to call onYouTubePlayerAPIReady for each one. You can pack all your player handlers in there at the same time, but depending on how you have to do it, that's not possible. Instead, you have to figure a way to trick the API. Take a look at my answer here loading multiple video players with youtube api

Categories