Skip to content Skip to sidebar Skip to footer

Youtube Player.destroy(); Throws 'this.a Is Null', Even When Validating Player

So I've got a small app with two panels. Using the iframe API. Clicking on one panel will expand the panel full screen, as well as showing a 'play video' button with some additiona

Solution 1:

The problem here is player is NOT undefined. What's happening is you have a global player reference, and you're doing the following with it:

  1. Creating a player in the first panel
  2. Destroying it when the first panel closes
  3. Calling player.stopVideo() on the already destroyed player (from the first panel) when the second panel closes

Currently, player holds a reference to whatever the last YouTube player you were using is, even if that player has already been destroyed.

What you should be doing is clearing out your reference to the player when you destroy it. Destroy won't (and can't) do that. You can also simplify your if condition since !player will check for null and undefined on its own:

var resetView = function() {
  // If a Youtube player is active, make sure we stop it.if (!player) {
    console.log("Player could not be found.");
  } else {
    player.stopVideo();
    player.destroy();
    player = null;  // Clear out the reference to the destroyed player
  }

Solution 2:

Highly inspired from IkeDoud's above answer and some others like this one, one year later, here is my way to avoid other video suggestions on play end in embedded API player:

<divid="player"></div><style>#player{
  min-width:auto;
  min-height:auto;
}
</style><script>// Load 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);

// Initialise the player with optionsvar player;
var playerOptions = {
  videoId: 'ViDeOiD_HeRe',
  events: {
    'onStateChange': onPlayerStateChange
  }
};

// Load the video whern player readyfunctiononYouTubeIframeAPIReady() {
  player = newYT.Player('player', playerOptions);
}

// On video end, reset the player back to poster imagefunctiononPlayerStateChange(event) {
  if(event.data === 0) {
    $(PaReNt_sElEcToR).find("#player").replaceWith('<div id="player"></div>');
    player = null;
    player = newYT.Player('player', playerOptions);
  }
}

</script>

No more irrelevant suggestions playable from the embedded video container. And no autoplay (mobile forbids it anyway) to have the poster (thumbnail) image.

On event.data === 0, which is video end... Destroy and reload the Iframe.

Post a Comment for "Youtube Player.destroy(); Throws 'this.a Is Null', Even When Validating Player"