Home > Software design >  Check if url works/ loads properly
Check if url works/ loads properly

Time:09-09

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')
  }
}

CodePudding user response:

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));

CodePudding user response:

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>

CodePudding user response:

You can use the onerror global attribute on a img element.

<img src="https://img.youtube.com/vi/Q5twKgxO8xg/maxresdefault.jpg" one rror="imageFailed()" />
function imageFailed() {
  console.log('Image URL does not works.');
}
  • Related