Check if Embedded YouTube Video has Finished - javascript

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.

Related

Autoplay videos from google drive and alert when they finish JavaScript

This is the code I use for autoplaying youtube videos:
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
height: '970',
width: '100%',
videoId: videos[index],
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// autoplay video
function onPlayerReady(event) {
event.target.playVideo();
}
// when video ends
function onPlayerStateChange(event) {
if(event.data === 0) {
location.reload();
}
}
And the html:
<script src="http://www.youtube.com/player_api"></script>
videos[index] - A variable in which all the videos are stored.
Is there any variation of the code that can play videos from google drive (or basically any code that can autoplay the video and alert when it's finished, it has to be in js)
I have looked for solutions to my problem for a few hours now and I tried them all out but without any success.
Does anyone have an idea on how I could accomplish this through JavaScript?
The answer is NO because Google Drive doesn't have an API, and it doesn't work like Youtube.

How to prioritize Javascript

I am dealing with this code written by somebody else and it is to load an image and a YouTube Video. My understanding his that I can change the priority of the script. Right now, it seems that when someone goes on this website with an iPhone and they hit the play button in front of the image, the video does not play, because the script is not finished loading. How do I alter the code below so that if the page or this script is not finished loading, the end user cannot see a play button?
By the way, this problem does not happen on an Android device, so I am not sure if that piece of information will serve as a clue.
I hope this makes sense because I am still trying to wrap my head around it.
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player1;
var player2;
function onYouTubeIframeAPIReady() {
player1 = new YT.Player('player', {
height: '390',
width: '640',
playerVars: {
'controls': 0,
'rel': 0
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
jQuery('.video-overlay').click(function() {
event.target.setVolume(100);
event.target.setPlaybackQuality('hd1080');
setTimeout(function() {
jQuery('.video-overlay').css('transform', 'scale(0)');
jQuery('.homepage-tagline').hide();
}, 300);
event.target.playVideo();
});
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
jQuery('.video-overlay').click(function() {
event.target.setPlaybackQuality('hd1080');
jQuery('.video-overlay').hide();
jQuery('.slider-overlay').hide();
event.target.playVideo();
});
}
function stopVideo() {
player.stopVideo();
}
I tried adding this piece of code:
jQuery('.video-overlay').css('opacity', 0);
but it didn't do much.
It would be best to set the pointer-events to none and when onPlayerReady is fired, set the target.style.pointerEvents = "all"

Simulate mouse click on Youtube videos on Android Kitkat

Youtube allows embedding user created playlist with the help of iframe code. I would like to embed them in a webpage to be played back on Android (Kitkat 4.4) tv box hardware. However it requires user to first click on the video.
As I found out that Apple iOS and Android disables autoplay on most mobile platforms to avoid poor user experiences
However, is it possible to simulate a user click on the iframe using Jquery or pure JS solution (preferred). Something like this:
function myFunction() {
setTimeout(function() { ("#myiframe").triggerHandler('click'); },3000)
};
I'd be very grateful if somebody can help me with this as this functionality is crucial for my purpose and I have searched extensively but couldn't get a proper solution.
thanks
dkj
Good morning dkjain,
as far as I've read in the Youtube Player API docs, there are several events triggered as soon as the Player is loaded, one of these events that should be used is the onReady() event.
Here's some updated code on how to auto-play a single video or a playlist:
HTML:
<div id="player"/>
will be the placeholder for the Youtube player
Playing a playlist (with playerVars):
JS:
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
playerVars: {
'listType': 'playlist',
'list': 'PLi5VEqNXXQjVJ4-xZb92wTUawkSQRal0u'
},
events: {
'onReady': onPlayerReady
}
});
}
window.onYouTubeIframeAPIReady = onYouTubeIframeAPIReady;
// as soon as the player is loaded, start the playback
function onPlayerReady(event) {
event.target.playVideo();
}
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/iframe_api";
document.head.appendChild(tag);
There is also an autoPlay: 1 playerVar, but this does not seem to be available on mobile plaforms: https://developers.google.com/youtube/iframe_api_reference#Mobile_considerations
Play a single video
JS:
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'nhX4rQ79C1A',
events: {
'onReady': onPlayerReady
}
});
}
window.onYouTubeIframeAPIReady = onYouTubeIframeAPIReady;
// as soon as the player is loaded, start the playback
function onPlayerReady(event) {
event.target.playVideo();
}
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/iframe_api";
document.head.appendChild(tag);
JSFiddles showing the above code:
Single video: http://jsfiddle.net/Moonbird_IT/akjpmvpf/
Playlist: http://jsfiddle.net/Moonbird_IT/akjpmvpf/4/ (updated again)
Let me know if we are going in the right direction :-)

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.

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