Detect when YouTube embedded video no longer playable?

Viewed 138

Is there a way to detect that an embedded YouTube video is not loading/playing due to content restrictions or removal? (as opposed to just the users internet...etc)

I have some YouTube videos embedded on a site. Every once in awhile, they become non-playable due to author taking down the content or making it no longer public, or whatever other reasons there may be.

The goal is to utilize some kind of detection/trigger to then be notified or take some action to ensure there aren't a bunch of stale/broken video embeds on my site.

I should be able to utilize the API to poll through each video and check its status, but would rather a more passive approach if possible (or maybe a combination of both, but would like to know what options are available).

2 Answers

You can use the embed code API. You could just check the duration of the video, if its zero, the video is failing to load.

https://developers.google.com/youtube/iframe_api_reference

      // with this modification
      function onPlayerReady(event) {
        if (player.getDuration() === 0) console.log("Failed to load video");
      }

I think you could use "onError" event from the API to know if the youtube video has failed to load.

function onYouTubeIframeAPIReady() {
  var player;
  player = new YT.Player('player', {
    width: 1280,
    height: 720,
    videoId: 'M7lc1UVf-VE',
    events: {
      'onReady': onPlayerReady,
      'onStateChange': onPlayerStateChange,
      'onError': onPlayerError
    }
  });
}

function onPlayerError(event) {
  // Handle error ere
}

Or if you are using some other API to get the video details, then check their official error documentation to find appropriate error codes for your issue. https://developers.google.com/youtube/v3/docs/errors

Related