0

I have an HTML img element like this:

<img src="https://theposterdb.com/api/assets/11949" />

And a CSS class like this:

div {
  background-image: url(https://theposterdb.com/api/assets/11949);
}

Both of these work and display the image on my site. However when I try to do the following in JavaScript:

fetch("https://theposterdb.com/api/assets/11949")

I get a CORS error. Why? I need to fetch the image in JS because I want to check if it was successfully loaded and otherwise display a custom alternative element.

Susccy
  • 214
  • 2
  • 13
  • 1
    because that's what CORS does - protects resources from unauthorised use - they are letting you use the image, but only as an image - you can, of course, use an onerror handler for the img tag to see if it was loaded – Bravo Aug 18 '21 at 11:29
  • 1
    You could try `img.addEventListener("load", ...)` to check if the image is loaded. – Kokodoko Aug 18 '21 at 11:30
  • one way to do it is to `fetch` through your server - then CORS doesn't apply - and - you can do a `HEAD` request to minimise the amount of response data - since you just want a 200 or 404 response status to check if the resource exists - what I don't understand is how you intend to fix CSS - but I guess you know what you're doing there – Bravo Aug 18 '21 at 12:09
  • @Bravo I didn't know servers could distinguish a GET request by an image element from a GET request by a fetch call. Is there some meta info in the headers that makes this possible? – Susccy Aug 18 '21 at 12:22
  • before going down the path you're leading yourself into ... *there is no backdoor around CORS* - the ONLY bypass is to make the request from your server ... browser requests your server, passing the URL to check, server checks, and returns a good/bad indication ... that's the only way to do it using fetch/xhr – Bravo Aug 18 '21 at 12:24
  • Can you use a service worker to intercept requests made from the html img and store the img or send the blob back to main thread? – cpakken May 15 '22 at 19:02

1 Answers1

1

You could use an event listener to check if the image is loaded.

HTML

<img id="test">

JS

let test = document.querySelector("#test")
test.addEventListener("load",()=>console.log("image was loaded!"))
test.src = "https://theposterdb.com/api/assets/11949"
Kokodoko
  • 26,167
  • 33
  • 120
  • 197
  • This does not answer the question. – Sean Aug 18 '21 at 11:34
  • 3
    The question also includes the text `I want to check if it was successfully loaded and otherwise display a custom alternative element.`... perhaps the OP doesn't need to know especially WHY cors prevents this and instead just needs a solution to the image loading check. – Kokodoko Aug 18 '21 at 11:41
  • Is there a way to check for a CSS background image too (like in my CSS example)? Edit: I believe I found the answer: https://stackoverflow.com/a/5058336/16503617 – Susccy Aug 18 '21 at 12:14