1

I'm trying to check if an image exists given a url using javascript, but my code is not working. Thanks!

Here's my function :

function verifyImageURL(url, callBack) {
  var img = new Image();
  img.src = url;
  img.onload = function () {
        callBack(true);
  };
  img.onerror = function () {
        callBack(false);
  };
}

And Here's how I call it:

var url = "http://greenstyle.com.br/wp-content/uploads/2012/09/Tucano-imagem-Silvia-Kochen-Wordpress.jpg";
verifyImageURL(url, function (imageExists) {
        if (imageExists === true) {
            alert("Image Exists");
        } else {
            alert("Image does not Exist");
        }
    });
8
  • 1
    What do you mean by it's not working? Do you get any errors? Does it always return true or false? Commented Nov 6, 2015 at 16:55
  • 1
    What's not working? what happens? Are there any console errors? - try asking a question other than saying 'my code doesn't work' Commented Nov 6, 2015 at 16:55
  • This code works for me: jsfiddle.net/wLb9tka7 Commented Nov 6, 2015 at 16:57
  • I want to call another function that creates an image on a table, where i have the alert, and it doesn't go to my function Commented Nov 6, 2015 at 17:00
  • @sergiogomesdev please show us this code, your function does work. There must be a logic problem with the asynchronous call. Commented Nov 6, 2015 at 17:04

2 Answers 2

0

Try this approach

var x = new XMLHttpRequest(); x.open("get", url, true);x.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) {alert('exist');}else{alert('does not exist'};}; x.send();
Sign up to request clarification or add additional context in comments.

Comments

0

This question hasn't had activity in a long time, but since I saw another recent answer, I thought I would share a solution which fits the asker's example pattern of using a callback, but alternatively returns a promise if no callback argument is provided:

See code in the TypeScript Playground to view types and the overloaded function signature

function loadImage (url, timeoutOrCallback, maybeCallback) {
  let timeout;
  let callback;

  if (typeof timeoutOrCallback === 'number') {
    timeout = timeoutOrCallback;
    if (typeof maybeCallback === 'function') callback = maybeCallback;
  }
  else if (typeof timeoutOrCallback === 'function') callback = timeoutOrCallback;

  const promise = callback
    ? undefined
    : new Promise(resolve => void (callback = resolve));

  const onlyRunOnce = {once: true};
  let timerId = 0;
  let done = false;

  if (typeof timeout === 'number') {
    timerId = setTimeout(() => {
      done = true;
      callback(false);
    }, timeout);
  }

  const img = new Image();

  img.addEventListener('load', () => {
    if (done) return;
    clearTimeout(timerId);
    done = true;
    callback(true);
  }, onlyRunOnce);

  img.addEventListener('error', () => {
    if (done) return;
    clearTimeout(timerId);
    done = true;
    callback(false);
  }, onlyRunOnce);

  img.src = url;
  return promise;
}


// Usage examples:

function asyncExample (url, logId) {
  const timeout = 3e3; // 3s

  loadImage(url, timeout).then(imageLoaded => {
    console.log(`${logId}: async with timeout:`, imageLoaded)
  });

  loadImage(url).then(imageLoaded => {
    console.log(`${logId}: async:`, imageLoaded)
  });
}

function callbackExample (url, logId) {
  const timeout = 3e3; // 3s

  let cb = imageLoaded => console.log(`${logId}: callback with timeout:`, imageLoaded);
  loadImage(url, timeout, cb);
  
  cb = imageLoaded => console.log(`${logId}: callback:`, imageLoaded);
  loadImage(url, cb);
}

let url = 'https://i.sstatic.net/TxzmG.jpg';
asyncExample(url, 'SO image');
callbackExample(url, 'SO image');

url = 'https://invalid.example/image.jpg';
asyncExample(url, 'invalid image');
callbackExample(url, 'invalid image');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.