skip to Main Content

I have a url. How can I check if that url works and displays the image and if the link doesn’t work or is broken I want to check if a different url works the if this one doesn’t work to just log all urls don’t work. How can I achieve this. Thanks in advance.

//I have a url like:
const myUrl = 'https://img.youtube.com/vi/Q5twKgxO8xg/maxresdefault.jpg'

//How can I check if th url work and if not try a different url
if (myUrl Works){
  console.log('url works')
} else {
  //check if this url works: 'https://img.youtube.com/vi/Q5twKgxO8xg/hqdefault.jpg'
  if (newUrl works) {
    console.log('new url works')
  } else {
    console.log('all urls broken')
  }
}

3

Answers


  1. You can use fetch API to check whether the image is available or not:

    fetch('https://img.youtube.com/vi/Q5twKgxO8xg/maxresdefault.jpg', {
      method: 'HEAD'
    }).then(res => {
      if (res.ok) {
        console.log('Image URL works.');
      } else {
        console.log('Image URL does not works.');
      }
    }).catch(err => console.log('Error:', err));
    
    Login or Signup to reply.
  2. You can use jQuery AJAX to check your image:

    const myUrl = 'https://img.youtube.com/vi/Q5twKgxO8xg/maxresdefault.jpg'
    $.ajax(myUrl, {
       type: "GET",
       crossDomain: true,
       error: function () {
            console.log('url broken')
       },
       complete: function(xhr, textStatus) {
            if (xhr.status == 200 && xhr.status == 301 && xhr.status == 302)
            {
                console.log('url work')
            }
        } 
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    Login or Signup to reply.
  3. You can use the onerror global attribute on a img element.

    <img src="https://img.youtube.com/vi/Q5twKgxO8xg/maxresdefault.jpg" onerror="imageFailed()" />
    
    function imageFailed() {
      console.log('Image URL does not works.');
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search