16

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...

Community
  • 1
  • 1
Rikard
  • 7,485
  • 11
  • 55
  • 92
  • 2
    This method will not work coz of Same origin policy. You will have to use a server side component to check if the URL exists. One option is using YQL as in this answer: http://stackoverflow.com/a/13041787/133198 – vsr Jul 20 '13 at 10:59
  • @vsr, thank you for the idea. Is there a client-side way to do this? – Rikard Jul 20 '13 at 11:05
  • 1
    Client-side is possible only when the host of the `url` supports CORS(http://www.html5rocks.com/en/tutorials/cors/). Since many sites don't support CORS, client-side solution is not fool-proof. – vsr Jul 20 '13 at 11:36
  • Duplicate of: http://stackoverflow.com/questions/3922989/how-to-check-if-page-exists-using-javascript – Matt Whipple Jul 20 '13 at 13:30
  • @MattWhipple, there is no plain javascript answer on that SO question/answer that is cross browser! There are some jQuery, which I didn't ask for. This is not duplicate at least of that question. – Rikard Jul 20 '13 at 13:48
  • @Rikard the technical limitations outlined in that question are not library specific however: the questions are the same because the implementation is irrelevant unless you refine what you're asking. – Matt Whipple Jul 20 '13 at 13:53
  • @MattWhipple, I did refine, on the title of my question, by writing "with javascript". But I can be more clear, and add that in the question body also. Will do that. – Rikard Jul 20 '13 at 13:58
  • @Rikard The other question is JS only also...the answers define constraints that must be met for any solution to be valid. Are you within these constraints? Have you responded to the previous comments here? – Matt Whipple Jul 20 '13 at 13:59
  • @MattWhipple, the answers in that question give solutions for url in same domain, it's not my case. My question is cross-domain. Do you know how to do this client-side? – Rikard Jul 20 '13 at 14:07
  • 5
    The only way to hack around SOP is to load the page in a way that the browser considers safer by using a hack with another element. I'd suggest trying the `onerror` handler for an `img` or possibly `object` tag to see if you can retreive the status code. In the past I've abused `iframe`s similarly but there are restrictions there (I've used it effectively with fire and forget calls and or when the iframe source explicitly calls back to the parent). – Matt Whipple Jul 20 '13 at 14:18

4 Answers4

4

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');
Chris Happy
  • 7,088
  • 2
  • 22
  • 49
  • When running this code from my website on GitHub Pages it works perfectly only when the target address is `https://`. It fails with Firefox error if the target address starts with `http://`. – WinEunuuchs2Unix Oct 25 '22 at 23:29
1

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.

  • 1
    http.open has the async parameter, when it's set as `false`, send() will not return until the end of response. However it's not suggested to be executed in the main thread. – Valen Jun 03 '17 at 08:37
1

You can not call services from different URL because of the 'Same Origin Policy' in JavaScript. Some workaround are presented here:

Ways to circumvent the same-origin policy

The most simple way is to use 'iframe'. By opening an iframe with your target url, you will be able to make http request to that url.

Saadat
  • 461
  • 6
  • 9
0

I saw your fiddle and it consists of 2 issues:

  1. DOM Exception
  2. CORS policy
  • You are getting DOM Exception because you are making synchronous calls.

Make the call synchronous by setting the last property to true

http.open('GET', url, true);

You can read the documentation here XMLHttpRequest Parameters

And also check this out: DOM Exception-failed-to-execute-send-on-xmlhttprequest-on-chrome-only

  • You can get an idea about the cors issue here
Abhishek Pankar
  • 723
  • 8
  • 26