Wednesday, June 12, 2013

Play YouTube Video with javascript and detect end of video


My client wanted to make a video ad where he spoke about potential advertiser's product and when the video was over Blogger needed to automatically redirect the browser to another website.

To play a video was straight forward using the YouTube Blogger icon, however, it didn't work with iPhone because iPhone doesn't support Flash.   Therefore, you need to use the embed YouTube link (with <iframe> tag) in order to get the video to work on iPhones.

Secondly, in order to determine when the video is finished playing, you need to use the javascript onPlayerState event callback.   This was a pain in the ass to figure out.    However, here is the completed code that works both on iPhone and desktops.   This is code that was directly put on a Blogger Page:
================

<script>
var isShowing = false;
var tag = document.createElement('script');
tag.src = "http://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: '320',
width: '180',
videoId: 'ENQ2_ZMAp5A',
playerVars: { 'controls': 0,'showinfo': 0, 'modestbranding': 1, 'autohide': 1, 'rel': 0, 'start': 0, 'autoplay': 1 },
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}

function onPlayerReady(event) {
if( isShowing )
player.playVideo();
}

function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.ENDED) {
location.href = "http://www.blessyourheart.com";
}
}

function playVideo() {
isShowing = true;
player.playVideo();
}
</script>


<div align="center">
   <div id="player"></div>
</div>

2 comments: