8

Youtube returns 404 for not existing thumbnails, but it also returns valid image data (broken video thumbnail), so checking it with Image does not work, onerror is not called:

var img = new Image();
img.onload = function() { alert("found")};
img.onerror = function() { alert("not found") };
img.src = "http://img.youtube.com/vi/aaaa/1.jpg";

When run then it says "found". Is there a way to detect 404 if the image data can actually be loaded?

It is also good if it shomehow can be detected that the link returns the standard youtube "broken video" thumbnail image data.

Tom
  • 7,515
  • 7
  • 38
  • 54
  • you could do it through the HTTP headers, but it will cost you a round trip. http://stackoverflow.com/questions/220231/accessing-the-web-pages-http-headers-in-javascript. ps; you would identify it by a http response code of 404 and a content-type of image/jpeg. – Marvin Smit Oct 15 '13 at 19:19
  • @Marvin Smit: but then I have to do an AJAX request towards youtube, don't I? Because I need the youtube image's headers, not the ones of the current document. And I can't send an ajax request to youtube, because of the same origin policy restriction. – Tom Oct 15 '13 at 19:27
  • Only possible if you could control the 'Access-Control-Allow-Origin' headers, which might be a none option next to the additional round trip for this, which is very likely costly. – Marvin Smit Oct 15 '13 at 19:49

1 Answers1

4

As a crude but working workaround in this case I would suggest checking the image's size on load. Usually the thumbnails are bigger, so if the returned image is 120x90px you can assume it's the 404 image.

The only other way will be to have it load via a PHP script that can check the HTTP Headers before passing through the image.

Jan Paepke
  • 1,997
  • 15
  • 25
  • That's a shame, but I think you're right. I just tried something like this: http://stackoverflow.com/questions/26630650/detect-404-error-on-page-load but it resulted in a cross domain error :/ – DAB Jan 12 '16 at 19:59