Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect when an image link returns 404, BUT it's still a valid image

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.

like image 781
Tom Avatar asked Oct 15 '13 19:10

Tom


People also ask

How do I know if my img src is valid?

To check if an img src is valid: Add an error event listener on the img element. If the src is invalid, set it to a backup image. Alternatively, hide the image.

How can I tell if a site is 404?

If you have ever wanted to check whether a page has returned a 404 for any reason, one of the easiest ways is to use this little helper function UrlExists() with the current url, given by window. location. href. This will return a true if the http status is anything except a 404, otherwise it will return false .


1 Answers

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.

like image 113
Jan Paepke Avatar answered Sep 24 '22 06:09

Jan Paepke