Given:
const img = document.getElementById('img-id');
img.onerror = function() { … };
img.src = new_url;
Changing the source of the image element may result in my very specific use case in either:
- A server status response
400 Bad Request, or - A server status response
200 OKwith aContent-TypeHTTP header that is not an image.
I would like to differentiate between both in the .onerror function.
I see the difference in the F12 console error of Chrome/Blink-based browsers and would like to capture this in a pure JavaScript conditional. Has the event related to .onerror any properties that may help to achieve this?
Note: This is for use in a progressive web application. By consequence, a solution that works with Chrome and Safari would suffice.
No you can't read the status code of a request made by an HTMLImageElement.
Your "400 Bad Request" response could still have a non null body, and even one that corresponds to a valid image.
It's frequent for instance for image services like imgur to return a valid placeholder image even when the request actually failed.
https://i.stack.imgur.com/foobar.png
In that case you won't have an error event at all, for what the browser is concerned, it did receive a valid image and could decode it.
If the browser fires an error event, it's always because the resource was not a valid image, never because of a response status.