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