Search code examples
videoyoutubedetection

Detect when YouTube embedded video no longer playable?


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).


Solution

  • 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