YouTube iframe player API - OnStateChange not firing

Solution 1:

There was a temporary issue with the iFrame Player API (which was fixed in June 2013) that you can read about 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/

As a temporary fix, you just need to add the event listener within the onReady event:

function onReady() {
    player.addEventListener('onStateChange', function(e) {
        console.log('State is:', e.data);
    });
}

Make sure to remove the onStateChange event from the YT.PLAYER constructor (see the jsfiddle).

Also, as someone mentioned on the Google Code Issue Thread, you set an interval and poll the player for its current state instead of listening for the onStateChange event. Here is an example code snippet for doing that:

setInterval( function() {
  var state = player.getPlayerState();
  if ( playerState !== state ) {
    onPlayerStateChange( {
      data: state
    });
  }
}, 10);

Firefox and IE Issues

Other people have mentioned that Firefox will not instantiate the YouTube Player if it is placed in a container with the css property display: none. Internet Explorer will also not work with visibility: hidden. If you're finding this to be the issue, try positioning the container off the page with something like left: -150%.

Steve Meisner talks about this here: YouTube API does not appear to load in Firefox, IFrame gets loaded , but the onPlayerReady event never fires?

And another related SO question: YouTube iframe API - onReady and onStateChanged events not firing in IE9

Edit: I've edited this answer to be more thorough because people are still seeing this error after the original bug was fixed in 2013.

Solution 2:

onStateChange does not work in any version of Internet Explorer or Edge. I assume it will begin working once Microsoft moves Edge over to being Chromium-based. But whether IE9, 11, or Edge, I cannot get this event to fire, even when it fires cleanly in Chrome, identical code.