YouTube Iframe API - OnStateChange suddenly not working [duplicate] - youtube-api

This question already has answers here:
YouTube iframe player API - OnStateChange not firing
(2 answers)
Closed 9 years ago.
Until around 6pm EST this code below would have worked fine, but now for some reason onStateChange is not firing. I've tried on multiple browsers and have had friends check it. See anything obviously wrong?
<div id="video">
<div id="player_wrap">
<div id="player"></div>
</div>
</div>
<script>
var tag = document.createElement("script");
tag.src = "http://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName("script")[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
function onYouTubeIframeAPIReady() {
var player;
player = new YT.Player("player", {
width: 640,
height: 400,
videoId: "MbfsFR0s-_A",
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady() {
alert ("player ready");
}
function onPlayerStateChange(event) {
alert ("something happened");
}

This is a temporary issue with the iFrame Player API. You can read about it here: https://code.google.com/p/gdata-issues/issues/detail?id=4706
Jeff Posnick posted a temporary workaround here: http://jsfiddle.net/jeffposnick/yhWsG/3/
Basically, you just need to add the event listener within the onReady event (just a temporary fix):
function onReady() {
player.addEventListener('onStateChange', function(e) {
console.log('State is:', e.data);
});
}

The solution posted here works fine and is REALLY clean:
player = new YT.Player(element,{
events: {
onReady: function(){
/*
Do your stuff
*/
// Attach a void function to the event
player.addEventListener('onStateChange',function(){});
},
onStateChange: function(){
// Actual function that gets executed during the event
}
}
});

Related

how to stop the youtube video playing in Ionic App

I am using IFrame for playing youtube video. It works fine but I want to stop it on button click. How to do it. Please help.
<div class="padding-css">
<iframe ng-model="myframe" class="frameclass" src="https://www.youtube.com/embed/CR5zjazP3hg?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>
</div>
Solution for Ionic2
ionViewWillLeave() {
let listaFrames = document.getElementsByTagName("iframe");
for (var index = 0; index < listaFrames.length; index++) {
let iframe = listaFrames[index].contentWindow;
iframe.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');
}
}
Don't forget to enable JS at the end of the video link *?enablejsapi=1
You can create iframe through java script and control player through buttons as stop.
<!DOCTYPE html>
<html>
<body>
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://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 player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
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) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
</script>
</body>
</html>
For more details you can go through this link.
https://developers.google.com/youtube/iframe_api_reference#Getting_Started

youtube api onPlayerStateChange not firing

i have looked through everything online and only see answers from a couple of years ago, and none of them help me. i see onYouTubeIframeAPIReady fire, but i never see onPlayerStateChange or onPlayerReady fire when the video plays or ends.
<iframe id="ytvideoframe1" width="100%" height="auto" src="https://www.youtube.com/embed/ZHqBp9vbO5E?enablejsapi=1&origin=http://www.earluminator.com"frameborder="0" allowfullscreen ></iframe>
<script>
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
console.log("onYouTubeIframeAPIReady");
player = new YT.Player('ytvideoframe1', {
playerVars: { 'controls': 0, 'modestbranding': 1, 'showinfo': 0 },
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
console.log("player1 created - onYouTubeIframeAPIReady");
}
function onPlayerReady(event) {
console.log("onPlayerReady");
player = new YT.Player('ytvideoframe1', {
playerVars: { 'controls': 0, 'modestbranding': 1, 'showinfo': 0 },
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerStateChange(event) {
console.log("onPlayerStateChange");
if ((event.data == YT.PlayerState.PLAYING ) ) {
console.log("PLAYING");
}
if ((event.data == YT.PlayerState.PAUSED ) ) {
console.log("PAUSED");
}
else {
console.log("OTHER");
}
}
Your onPlayerReady is not firing because as opposed to the suggested implementation here, your onPlayerReady is calling itself with the onReady event. Seems like you copied over the onYouTubeIframeAPIReady() code and forgot to make changes. As mentioned in the documentation linked above, I would suggest to change your onPlayerReady implementation as shown
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
Consequently, your onPlayerStateChange is not firing because according to your code, it is not getting there. Fixing your onPlayerReady should fix this problem as well.

YouTube API - Enbedding By URL

I want to Embed A youtube video by url, example= https://gdata.youtube.com/feeds/api/users/estXcrew/uploads?max-results=1
This Is the block of code that I used
<div id="player"></div>
<script>
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '200',
width: '200',
videoId: '//video ID Usually goes here',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
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();
}
</script>
I Copied this code from the Site of the Youtube API since I don't have much experience with it yet. How do I replace the "videoId" Line with the link above?
To load a YouTube video replace
//video ID Usually goes here
with the ID of the video you want to load.
Example YouTube video: http://www.youtube.com/watch?v=xmP7kQdAPhM
Now in the videoId I would use
videoId: 'xmP7kQdAPhM'
Or if you used some PHP you could try something like the following.
<?php
$feedURL = 'http://gdata.youtube.com/feeds/api/users/estXcrew/uploads?max-results=1';
$sxml = simplexml_load_file($feedURL);
$i=0;
foreach ($sxml->entry as $entry) {
$media = $entry->children('media', true);
$watch = (string)$media->group->player->attributes()->url;
$pat = '/\=([^\"]*?)\&/';
$value=$watch ;
preg_match($pat, $value, $matches);
echo "<iframe title='YouTube video player' class='youtube-player' type='text/html'
width='640' height='390' src='http://www.youtube.com/embed/$matches[1]'
frameborder='0' allowFullScreen></iframe>";
?>
<div class="videoitem">
<div class="videotitle">
<h3><?php echo $media->group->title; ?></h3>
<p><?php echo $media->group->description; ?></p>
</div>
</div>
<?php $i++; if($i==3) { echo '<div class="clear small_v_margin"></div>'; $i=0; } } ?>
Example
First, about the url. Note that this url means using version 2 and that this version has been deprecated. See "YouTube API Subject to the Deprecation Policy": https://developers.google.com/youtube/youtube-api-list
Note also, that by default version 1 is used and you may want to add: v=2, for version 2. If you prefer the response in JSON instead of XML, then add: alt=json. For better reading add: prettyprint=true.
For example:
https://gdata.youtube.com/feeds/api/users/estXcrew/uploads?maxresults=1&v=2&alt=json&prettyprint=true
Further, since JSON is used in api version 3, you may prefer JSON to be used. For using api version 3 it is necessary to obtain an api-key first, by registering.
To capture the response, you need to send the url to the server using XMLHttpRequest() or ActiveXObject().
Look for (JS or other type) code libraries that may help you, for example to parse and compose XML or JSON strings; or send url requests.
See for jSON parsing: Parse JSON in JavaScript?
About your code supplied: use parameters. For example, after getting a videoId:
<!DOCTYPE html>
<html>
<head>
<!--
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
// Adding a library to send requests to a server ?
</script>
-->
<script>
var myVideoId = "ZY7aRxb-Z1c"; // Set the videoId here.
// insert an iframe
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player; // reference to the player object
var param = { // video-player parameters
height: '200',
width: '200',
videoId: 'xxxxxxxxxxx',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
};
param.videoId = myVideoId // Replace the videoId parameter
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', param); // create the player object
}
function onPlayerReady(event) {
event.target.playVideo(); // start to play
}
var done = false; // flag
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
//setTimeout(stopVideo, 6000); // This will stop playing after 6 seconds
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
</script>
</head>
<body>
<div id="player">please wait...</div>
</body>
</html>

How can I get jCarousel to pause when a YouTube video is playing?

I have a jCarousel (jquery) running for several youtube videos. The carousel works great, and even pauses when you hover on a slide- but it will resume if you move your cursor off the slide, even if the video is playing.
Videos are embedded using the YouTube Player API.
Plugin: http://sorgalla.com/jcarousel/
This is the Carousel code I'm using:
<script type="text/javascript">
function mycarousel_initCallback(carousel, item, idx, state){
// Disable autoscrolling if the user clicks the prev or next button.
carousel.buttonNext.bind('click', function() {
carousel.startAuto(0);
});
carousel.buttonPrev.bind('click', function() {
carousel.startAuto(0);
});
// Pause autoscrolling if the user moves with the cursor over the clip.
$('#mycarousel').hover(function() {
carousel.stopAuto();
}, function() {
carousel.startAuto();
});
};
$(function() {
$('#mycarousel').jcarousel({
auto: 2,
wrap: 'both',
initCallback: mycarousel_initCallback
});
});
</script>
The YouTube script:
<script>
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var done = false;
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
height: '505', // 535
width: '900',
videoId: 'DxZve0UV6UM',
playerVars: {
'autoplay': 0,
'controls': 0,
'modestbranding': 1,
'wmode': 'opaque'
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(evt) {
player.setPlaybackQuality('hd720');
}
function onPlayerStateChange(evt) {
if (evt.data == YT.PlayerState.PLAYING && !done) {
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
</script>
And the HTML...
<ul id="mycarousel" class="jcarousel-skin-tango">
<li>
<div id="player"></div>
</li>
<li>
<div id="player"></div>
</li>
</ul>
Any suggestions?
Simply call carousel.startAuto() and carousel.stopAuto() when the player triggers an event:
function onPlayerStateChange(evt) {
if(evt.data == YT.PlayerState.PLAYING) {
global_carousel.stopAuto(); // Stop the carousel, if video is playing
} else {
global_carousel.startAuto(); // Otherwise, start it
}
}
Edit:
Make the variable carousel global inside mycarousel_initCallback:
var global_carousel;
function mycarousel_initCallback(carousel, item, idx, state) {
global_carousel = carousel;
//Other code
Then use that instead in the code before (as I've edited).

How make fancybox auto close when youtube video id done?

How i can make fancybox auto close when youtube video ended?
This isn't as simple as it sounds:
First determine if you are going to use the embed or iframe player.
Follow the embed player API or iframe player API examples to initialize the API.
Use the "onComplete" fancybox callback functon to set up the player once the popup is open.
In the callback, make sure you add an onStateChange event listener so you can determine when the video has completed (the value of zero means the video has ended)
Once you find that the video has ended, then use the $.fancybox.close method to close the popup
or, you could just let the user close the popup.
this is the full script with Fancybox-Youtube-Cookie-Autoclose-Autopopup just download the images that required in css put them in /fancybox folder in your root and replace with your video id. Really works fully tested...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/2.1.5/jquery.fancybox.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/2.1.5/helpers/jquery.fancybox-media.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/2.1.5/jquery.fancybox.min.css" media="screen" />
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
<script src="http://www.youtube.com/player_api"></script>
<script type="text/javascript">
// detect mobile devices features
var isTouchSupported = 'ontouchstart' in window,
isTouchSupportedIE10 = navigator.userAgent.match(/Touch/i) != null;
function onPlayerReady(event) {
if (!(isTouchSupported || isTouchSupportedIE10)) {
// this is NOT a mobile device so autoplay
event.target.playVideo();
}
}
function onPlayerStateChange(event) {
if (event.data === 0) {
$.fancybox.close();
}
}
function onYouTubePlayerAPIReady() {
$(function() {
if ($.cookie('welcome_video')) {
// it hasn't been three days yet
} else {
// set cookie to expire in 3 days
$.cookie('welcome_video', 'true', { expires: 3});
$(document).ready(function () {
$.fancybox.open({
href: "https://www.youtube.com/embed/qm1RjPM9E-g", /*YOUR VIDEO ID*/
helpers: {
media: {
youtube: {
params: {
autoplay: 1,
rel: 0,
// controls: 0,
showinfo: 0,
autohide: 1,
}
}
},
buttons: {}
},
beforeShow: function () {
var id = $.fancybox.inner.find('iframe').attr('id');
var player = new YT.Player(id, {
events: {
onReady: onPlayerReady,
onStateChange: onPlayerStateChange
}
});
}
}); // fancybox
}); // ready
} // cookie else ready
}); // function for cookie
} // youtube API ready
</script>
After looking around without any luck here is a solution I came up with
See what we do, watch a video here
<div style="display: none;">
<div id="player"></div>
</div>
<script src="http://www.youtube.com/player_api"></script>
<script>
$(document).ready(function () {
$("a.video_button").fancybox({
'titlePosition' : 'inside',
'transitionIn' : 'none',
'transitionOut' : 'none'
});
});
// create youtube player
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 's19V_6Ay4No',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// autoplay video
function onPlayerReady(event) {
}
// when video ends
function onPlayerStateChange(event) {
if(event.data === 0) {
$(document).ready(function () { parent.$.fancybox.close();});
}
}
</script>
Yes this is the right way to handle to fancybox or colorbox. Youtube Video API provides different states to handle this like unstarted=-1, ended=0, playing=1, paused=2, buffering=3, video cued=5
Getting or traping this state in fancybox jquery code block one can achieve this easily. Just visit this article with proper demo also.Visit here

Resources