Check if cross domain url gives 404 with javascript
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');
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.
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.