YouTube IFrame API with existing IFrame failing to run callbacks - javascript

Somewhat related to:
YouTube IFrame API doesn't always load?
But different in that I AM loading the YouTube script per instructions. Note, in my source, the iframe is ABOVE the script block in the load order. I based this off of these instructions (below). The example works fine if I'm on that page, but doesn't seem to work for me when I put the code on mine. I'm sure I'm missing something really simple but I'm to be missing it. Thanks!
https://developers.google.com/youtube/iframe_api_reference#Mobile_considerations
var tag = document.createElement('script');
tag.src = 'https://www.youtube.com/iframe_api';
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
//Console shows this script is loading
var player;
function onYouTubeIframeAPIReady() {
console.log("onYouTubeIframeAPIReady", arguments); //This shows in console
player = new YT.Player('js_youTubeFrame', {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
console.log("onPlayerReady",event); //Never triggers
}
function onPlayerStateChange(event) {
console.log("onPlayerStateChange", event); //Never triggers
if (event.data === YT.PlayerState.PLAYING) {
console.log("YouTube Video is PLAYING!!"); //Never triggers
}
}
<div id="js_youTubeContainer" class="embed-responsive embed-responsive-16by9">
<iframe id="js_youTubeFrame" class="embed-responsive-item" src="https://www.youtube-nocookie.com/embed/u3A7bmEOtaU?enablejsapi=1&rel=0&showinfo=0" frameborder="0" allowfullscreen></iframe>
</div>

Best way to load a Youtube Video by his API, is following this sintaxis:
<div id="video-youtube"></div>
<script id="youtube-tracking-script">
var youtubeVideoId = 'u3A7bmEOtaU'; // replace with your own video id
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementById("youtube-tracking-script");
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var video;
function onYouTubeIframeAPIReady() {
video = new YT.Player('video-youtube', {
height: '352',
width: '100%',
videoId: youtubeVideoId,
playerVars: {rel: 0, showinfo: 0},
events: {
'onStateChange': videoPlay
}
});
}
function videoPlay(event) {
if (event.data == YT.PlayerState.PLAYING) {
console.log("YouTube Video is PLAYING!!");
}
if (event.data == YT.PlayerState.PAUSED) {
console.log("YouTube Video is PAUSED!!");
}
if (event.data == YT.PlayerState.ENDED) {
console.log("YouTube Video is ENDING!!");
}
}
</script>
https://jsfiddle.net/t4qwfk0d/1/

You should replace your <iframe> </iframe> to <div id= "js_youTubeFrame"> </div>, in my case it works.
I think that Youtube Iframe Api needs that div to convert it on iframe after.

Related

cant get youtube video current time

I have an embedded YouTube videos in my HTML page. I'm trying to get the current time of YouTube video. I used the answer of that question to create page like this
(YouTube currentTime with jQuery)
When I'm trying to display the time I'm getting an error: 'getCurrentTime is not a function'.
HTML
<div style="text-align:center">
<button onclick="playPause()">Play</button>
<button onclick="showTime()">Show Time</button>
<br><br>
<iframe id = "it" width="560" height="315" src="https://www.youtube.com/v/FHtvDA0W34I?version=3&enablejsapi=1" frameborder="0" allowfullscreen></iframe>
<br>
<label id=startHighlighlbl>VideoHighlightStart: </label>
</div>
JavaScript
<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', {
events: {
'onReady': onPlayerReady
}
});
}
function onPlayerReady(event) {
event.target.playVideo();
}
function ShowTime() {
alert(player.getCurrentTime());
}
</script>
You should load your video through the YT-API, so player is initialized correctly and thus accessible through the API. Basically you need to remove your iframe from your HTML and instead let YT-API create the iframe for you.
Try the following:
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('it', {
height: '315',
width: '560',
videoId: 'FHtvDA0W34I',
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();
}
function ShowTime() {
alert(player.getCurrentTime());
}
<body>
<button onclick="ShowTime()">Show Time</button>
<br>
<div id="it"></div>
</body

Pass youtube iframe api events onstatechange when src changes

So I figured I would update this with a working example. I have ditched stating the iframe tag and just used the iframe api to create an iframe and then loaded the player by id with a data attribute. Here is a working example below. So now all statechanges are passed consistently through the youtube player. So the script will load an iframe into the Div #player and you can just loadVideoByID pretty easily with jquery and javascript.
<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', {
playerVars: { 'autoplay': 0,},
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
alert('started');
}
function onPlayerStateChange(event) {
if(event.data === 0) {
alert('done');
}
}
$( document ).on( "click", ".video-link", function(e) {
e.preventDefault();
var videoID = $(this).attr('data-videoID');
player.loadVideoById(videoID);
});
</script>
And then use a link with a data-attribute like so.
Link
Rather than having buttons to play, why not cue to playlist when the player is ready? You can hold the video ID's in an array... If this isn't what you're looking for just leave a comment below and I will change things the best I can to fit.
//Array of videos
var MyVideos=["E6RGMRamAFk","IHQr0HCIN2w","CogIXrea6A4"];
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', {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
//Player is ready, cue the array of videos into the playlist.
player.cuePlaylist(MyVideos);
}
function onPlayerStateChange(event) {
}
JS Fiddle - Working Demo
YouTube JavaScript Player API Reference
If you have any questions please leave a comment below and I will get back to you as soon as possible.
I hope this help. Happy coding!

Youtube SeekTo Suddenly stopped working - Looping video?

So from what I can gather one or two things are going from with my youtube video's either the seekTo function has stopped working or the hole API has....(Or youtube has changed something) Now please take in mind my codes were working flawlessly without fault untill yesterday... (code usually doesn't break over night).
Here are 2 sites with the SeekTo function that loops the video via PlayerState ENDED:
http://imvu.url.ph/aattpx/DC_MAR/Base/XML/COMPIC_X1/2014/LayDStroke/maintemp/index.html
http://imvu.url.ph/FTP/2013/System/Core/Int/Warning/Dont_Not_Touch/DKLAY2013BLUE/Layout/Infuriate/index.html
The codes for the youtube video are more or less identical so I'll just post 1 of the codes:
view-source:imvu.url.ph/aattpx/DC_MAR/Base/XML/COMPIC_X1/2014/LayDStroke/maintemp/video.html
<div id="youtube-fs"><iframe id="youtube-iframe" type="text/html" src="http://www.youtube.com/embed/o2cvRsiRkqs?enablejsapi=1&autoplay=1&showinfo=0&iv_load_policy=3&controls=0&rel=0&wmode=transparent&vq=hd720&hd=1&loop=1" frameborder="0" wmode="Opaque" ></iframe> <script type="text/javascript">
<!--
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 player;
player.quality = 'hd720';
function onYouTubePlayerAPIReady() { player = new YT.Player('youtube-iframe', { events: { 'onStateChange': onPlayerStateChange } }); }
function onPlayerReady(event) { event.target.setPlaybackQuality('hd720'); event.target.playVideo(); }
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.BUFFERING) {
event.target.setPlaybackQuality('hd720');
}
if (event.data == YT.PlayerState.ENDED) { player.seekTo(0, true); } // end if
}
-->
</script>
</div>
</div></div>

youtube reference api for iFrame embeds is not loading iFrame

I have used the code refering https://developers.google.com/youtube/iframe_api_reference#Getting_Started. I have copied the same code as provided in above url. But, it gives me a blank page.
<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>
Can anyone please help me to resolve this issue?
This code seems good. What did you paste it in? Maybe it's an unrelated syntax error...

Youtube delay auto start video

There is anyway to delay the auto start of a youtube video for example:" 20seconds, after page loads?"
Here is the example just with the auto start:
http://jsfiddle.net/qbqEA/
Thanks
It is not perfect solution but it works,
<iframe class="delayed" width="486" height="273" frameborder="0" data-src="__url__" allowfullscreen=""></iframe>
note that I used data-src instead of 'src'
$(document).ready(function() {
setTimeout(function() {
$('iframe.delayed').attr('src',
$('iframe.delayed').attr('data-src'));
}, 20000);
}
It will load iframe 20 seconds after page loads.
see my fork: http://jsfiddle.net/WswGV/
The best way to do it is to use YouTube.API with Javascript functionality.
// Load the IFrame Player API code asynchronously.
setTimeout(function() {
player.playVideo();
}, 20000);
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// Replace the 'ytplayer' element with an <iframe> and
// YouTube player after the API code downloads.
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('ytplayer', {
height: '315',
width: '560',
videoId: 'I_V_kIzKKqM'
});
}
I hope this help
The link to the IFrame YouTube API above is obsolete, I think, but here's one I found today:
https://developers.google.com/youtube/iframe_api_reference
Wish I'd read that a long time ago.
To excerpt from the example there, I would suggest that you detect the player being downloaded and ready, then set a timer for the desired number of seconds (20 in your case, I think), and then play the video.
---v
Using https://developers.google.com/youtube/iframe_api_reference this will add a 10 second delay before the video automatically starts:
<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: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
setTimeout(function() {
event.target.playVideo();
}, 10000);
}
function stopVideo() {
player.stopVideo();
}
</script>
I use the following function
jQuery(document).ready(function () {
var frame = jQuery('.embed-responsive iframe');
var src = frame.attr('src');
setTimeout(function(){ frame.attr('src', src+'?autoplay=1'); }, 20000);
});

Categories