How to detect when a youtube video finishes playing?

JavascriptFlashApiActionscriptYoutube

Javascript Problem Overview


I am working on a site that has a ton of embedded youtube videos, the client wants to show a popup whenever a video stops splaying.

I looked at the youtube api and there seems to be a way to detect when a video ends:

http://code.google.com/apis/youtube/js_api_reference.html

but I can't embed the videos like they mentioned on that page since the videos are all already on the site (thousands that have been added manually by pasting embed code).

Is there a way to detect the ending of these videos without changing any of the existing videos (using javascript)?

Javascript Solutions


Solution 1 - Javascript

This can be done through the youtube player API:

http://jsfiddle.net/7Gznb/

Working example:

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

	<script src="http://www.youtube.com/player_api"></script>
	
    <script>
		
		// create youtube player
		var player;
		function onYouTubePlayerAPIReady() {
			player = new YT.Player('player', {
              width: '640',
			  height: '390',
			  videoId: '0Bmhjf0rKe8',
			  events: {
				onReady: onPlayerReady,
				onStateChange: onPlayerStateChange
			  }
			});
		}

		// autoplay video
		function onPlayerReady(event) {
			event.target.playVideo();
		}

		// when video ends
		function onPlayerStateChange(event) {        
			if(event.data === 0) {			
				alert('done');
			}
		}
		
	</script>

Solution 2 - Javascript

What you may want to do is include a script on all pages that does the following ...

  1. find the youtube-iframe : searching for it by width and height by title or by finding www.youtube.com in its source. You can do that by ...
  • looping through the window.frames by a for-in loop and then filter out by the properties
  1. inject jscript in the iframe of the current page adding the onYoutubePlayerReady must-include-function http://shazwazza.com/post/Injecting-JavaScript-into-other-frames.aspx

  2. Add the event listeners etc..

Hope this helps

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser967451View Question on Stackoverflow
Solution 1 - Javascriptuser967451View Answer on Stackoverflow
Solution 2 - JavascriptyshoumanView Answer on Stackoverflow