0

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')
  }
}
seriously
  • 1,202
  • 5
  • 23
  • Does this answer your question? [Check if image exists on server using JavaScript?](https://stackoverflow.com/questions/18837735/check-if-image-exists-on-server-using-javascript) – Idrizi.A Sep 08 '22 at 11:07
  • @Enve no both good and bad links in responding good – seriously Sep 08 '22 at 11:17
  • The code works, but img.youtube.com always returns a valid placeholder image. There is probably no way to tell – Idrizi.A Sep 08 '22 at 11:29

3 Answers3

0

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));
DCodeMania
  • 1,027
  • 2
  • 7
  • 19
0

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>
Alex J
  • 162
  • 8
  • in this code, if URL redirecting, they said ```url work```. To stop that, simply remove the ```xhr.status == 301 && xhr.status == 302``` in code – Alex J Sep 08 '22 at 13:02
  • This also won't work across domains because of CORS. – Fred Sep 08 '22 at 13:03
  • I added ```crossDomain: true``` before. in my case it's work without any problem – Alex J Sep 08 '22 at 13:11
  • this doesn't work for example this https://img.youtube.com/vi/Q5twKgxO8xg/hqdefault.jpg works but function return url broken – seriously Sep 08 '22 at 23:44
0

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.');
}
Fred
  • 12,086
  • 7
  • 60
  • 83