Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a URL is broken in Javascript

Tags:

This question has been posted on Stack before, but none so specific as to what I'm trying to understand.

The simplest way to check if a URL is corrrect to send a http Head request. But how do you use that to specify the URL ?

I found this in a previous post :

function UrlExists(url) {   var http = new XMLHttpRequest();   http.open('HEAD', url, false);   http.send();   return http.status!=404; } 

But it doesn't seem to run in firebug for a few reasons.

My apologies ahead of time for being daft.

like image 532
Trip Avatar asked Oct 12 '10 14:10

Trip


People also ask

How check URL is checked or not in jquery?

var urlExists = function(url){ //When I call the function, code is still executing here. $. ajax({ type: 'HEAD', url: url, success: function() { return true; }, error: function() { return false; } }); //But not here... }


2 Answers

I'd recommend to use jQuery for correct cross-browser ajax requests:

function UrlExists(url, cb){     jQuery.ajax({         url:      url,         dataType: 'text',         type:     'GET',         complete:  function(xhr){             if(typeof cb === 'function')                cb.apply(this, [xhr.status]);         }     }); } 

Usage:

UrlExists('/path/script.pl', function(status){     if(status === 200){        // file was found     }     else if(status === 404){        // 404 not found     } }); 
like image 168
jAndy Avatar answered Sep 22 '22 07:09

jAndy


Modern, cross and short way

checkLink = async url => (await fetch(url)).ok 

which is same of:

async checkLink(url) { return (await fetch(url)).ok } 

which is same of:

async function checkLink(url) { return (await fetch(url)).ok } 

which is same of:

Note: Starting with Gecko 30.0 (Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27), Blink 39.0, and Edge 13, synchronous requests on the main thread have been deprecated due to their negative impact on the user experience.

Cross solution (old, deprecated)

function UrlExists(url) {  var http = new XMLHttpRequest();  http.open('HEAD', url, false);  http.send();  return http.status==200; } 
like image 35
insign Avatar answered Sep 20 '22 07:09

insign