1

First, let's everybody look at this adorable owl:

http://happy.fm/wp-content/uploads/2011/10/random-owl.jpg

I'm using that as a test image to see if I can detect, using client-side Javascript, whether a given URL is a legit image. I hunted around online and found some simple code that's supposed to work:

const img = new Image();
img.onload = () => {
    console.log("HOORAY! SUCCESS!", img);
}

img.onerror = () => {
    console.log("BOO! FAIL!")
}

img.src = values.image;

If I put in a URL which has a valid domain, but bad file path, like this:

http://happy.fm/wp-content/uploads/2011/10/random-owlDOESNOTEXIST.jpg

...then onerror() fires reliably. However, if the domain is bogus, like this:

http://happy.fmDOESNOTEXIST/wp-content/uploads/2011/10/random-owl.jpg

...then onerror() never fires. Is this, like, expected behavior? Is there any way around this?

And yes, I realize doing only client-side validation isn't the best way to really handle this issue, but pretend for the moment that this is the only way.

EDIT: it's worth mentioning that I'm seeing this error in a Node.js/Webpack local environment, running on top of the webpack-dev-server. Maybe this becomes some sort of permissions problem.

hairbo
  • 3,113
  • 2
  • 27
  • 34
  • That's odd behavior. You could check if the url exists using something like this, https://stackoverflow.com/questions/10926880/using-javascript-to-detect-whether-the-url-exists-before-display-in-iframe . Would this suffice for an answer? – Tennyson H Feb 10 '16 at 17:02
  • 1
    I cant seem to reproduce [the error](https://jsfiddle.net/59bhj75r/), as in, onerror seems to be firing as expected – Sterling Archer Feb 10 '16 at 17:03
  • If you are doing this in WordPress you can bind `site_url()` at begining and get the images – Vasim Shaikh Feb 10 '16 at 17:07
  • @TennysonH: I can't do that, because it requires same domain, and this is cross-domain. – hairbo Feb 10 '16 at 17:34
  • @SterlingArcher: this is weird. I see that it works on JSFiddle as well. I'm running locally in a Node.js/Webpack environment (localhost:3000). Maybe that's the issue here. I'll see if I can test on a published version of my project. – hairbo Feb 10 '16 at 17:34

1 Answers1

0

Okay, I'm an idiot. I had an upstream check to validate whether or not the inbound URL was in a valid format. When I checked the domain, I did this:

http://happy.f/wp-content/uploads/2011/10/random-owl.jpg

It's not legal to have a top-level domain that's a single character, so my validate routine caught that. As soon as I put in a validly-formatted-but-still-bogus top-level domain, like this:

http://happy.fasdfasdfasdfasdf/wp-content/uploads/2011/10/random-owl.jpg

my onerror() method fired.

So...d'oh.

hairbo
  • 3,113
  • 2
  • 27
  • 34