3

I've some videos integrated through WordPress as iframe.

What I'm looking for is to redirect users to the homepage as soon as the video finishes playing.

Is there any event in Javascript to catch when existing Youtube video stops?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
aumio
  • 63
  • 11
  • Check this post for details http://stackoverflow.com/questions/10773322/event-when-youtube-video-finished – sathishn Jul 20 '14 at 08:22
  • Thanks a lot. I've checked that already. But I thought the post is from 2012 and It's Mid of 2014. 2 of these years nothing have been changed? However thanks a lot. Do you think it'll work on existing iframes? not youtube api generated iframes. – aumio Jul 20 '14 at 08:34
  • Also if you could help me little bit on this. Where the "player" object comes from? How to define the player object? – aumio Jul 20 '14 at 08:36
  • how many iframe videos do you have in the page? – sathishn Jul 20 '14 at 08:43
  • I have one video in each page. Total 10-12 videos on individual pages. Will be adding more. – aumio Jul 20 '14 at 09:14
  • This should help you http://stackoverflow.com/questions/7443578/youtube-iframe-api-how-do-i-control-a-iframe-player-thats-already-in-the-html – sathishn Jul 20 '14 at 09:18
  • Seen that as well. :) Couldn't make this working yet. :( – aumio Jul 20 '14 at 09:31
  • did you try the below code? – sathishn Jul 21 '14 at 08:12
  • Yes. I already did. It didn't work. However I'm giving it another and try and letting you know if it's working. Thanks. – aumio Jul 21 '14 at 09:56
  • Can you paste your code that you are trying here – sathishn Jul 21 '14 at 10:29

1 Answers1

3
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() {
    // first video
    player = new YT.Player('player', {
        events: {
            'onReady': function(){ alert("Ready!"); },
            'onStateChange': onPlayerStateChange
        }
    });
}

function onPlayerStateChange(event) {
    if (event.data == YT.PlayerState.ENDED) {
        console.log('player stopped');
    }
}

Above code will work if your iframe looks as below

<iframe id="player" width="640" height="360" src="https://www.youtube.com/embed/ZdP0KM49IVk?enablejsapi=1" frameborder="0" allowfullscreen />

with id=player and ?enablejsapi=1

sathishn
  • 150
  • 4
  • Thanks a lot sathishn. You made my day. It's working now. :) I made a silly mistake that time. I didn't remove the oembed from the url generated by WordPress. Take Care – aumio Jul 21 '14 at 20:24
  • enablejsapi=1 saved me. Thanks – Philip May 13 '15 at 13:50