Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if cross domain url gives 404 with javascript

I am trying this code but it gives me a DOM Exception. What I want it to get a true/false "answer" from the function using plain Javascript.

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

FIDDLE

I got this code from this SO answer, but as said I cannot get it working...

like image 325
Rikard Avatar asked Jul 20 '13 10:07

Rikard


People also ask

How do you check if a URL exists or returns 404 with JavaScript?

If you have ever wanted to check whether a page has returned a 404 for any reason, one of the easiest ways is to use this little helper function UrlExists() with the current url, given by window. location. href. This will return a true if the http status is anything except a 404, otherwise it will return false .

How do you check the URL is working or not in JavaScript?

You can use the URLConstructor to check if a string is a valid URL. URLConstructor ( new URL(url) ) returns a newly created URL object defined by the URL parameters. A JavaScript TypeError exception is thrown if the given URL is not valid.

Why am I getting a 404 error?

404 error codes are generated when a user attempts to access a webpage that does not exist, has been moved, or has a dead or broken link. The 404 error code is one of the most frequent errors a web user encounters. Servers are required to respond to client requests, such as when a user attempts to visit a webpage.


2 Answers

Cross domain does not give any status code. status code is part of the content which is received from server when server responds with yes or no. In case of cross domain server never respond to request.

the second mistake in the code is you cannot capture the status code directly without any waiting time or success event. return statement in function doesn't wait until server response to ajax request, so you cannot depend on it.

like image 171
roudrabhaskarudu thammali Avatar answered Oct 18 '22 02:10

roudrabhaskarudu thammali


Doesn't detect 404 errors, but can check if the page exists or not with a setTimeout() hack.

// Based on https://stackoverflow.com/a/18552771
// @author Irvin Dominin <https://stackoverflow.com/u/975520>
function UrlExists(url)
{
  var iframe = document.createElement('iframe');
  var iframeError; // Store the iframe timeout
  
  iframe.onload = function () {
    console.log("Success on " + url);
    clearTimeout(iframeError);
  }
  
  iframeError = setTimeout(function () {
    console.log("Error on " + url)
  }, 3000);
  
  iframe.src = url;
  document.getElementsByTagName("body")[0].appendChild(iframe);
}

UrlExists('http://www.google.com/');
UrlExists('http://www.goo000gle.com');
like image 43
Chris Happy Avatar answered Oct 18 '22 01:10

Chris Happy