I'm using javascript to pass a dynamic url to iframe src. but sometimes the url does not exist, how could i detect the non-exist url beforehand, so that i can hide the iframe that with 404 error.
8 Answers
Due to my low reputation I couldn't comment on Derek 朕會功夫's answer. I've tried that code as it is and it didn't work well. There are three issues on Derek 朕會功夫's code.
The first is that the time to async send the request and change its property 'status' is slower than to execute the next expression - if(request.status === "404"). So the request.status will eventually, due to internet band, remain on status 0 (zero), and it won't achieve the code right below if. To fix that is easy: change 'true' to 'false' on method open of the ajax request. This will cause a brief (or not so) block on your code (due to synchronous call), but will change the status of the request before reaching the test on if.
The second is that the status is an integer. Using '===' javascript comparison operator you're trying to compare if the left side object is identical to one on the right side. To make this work there are two ways:
- Remove the quotes that surrounds 404, making it an integer;
- Use the javascript's operator '==' so you will be testing if the two objects are similar.
The third is that the object XMLHttpRequest only works on newer browsers (Firefox, Chrome and IE7+). If you want that snippet to work on all browsers you have to do in the way W3Schools suggests: w3schools ajax
The code that really worked for me was:
var request;
if(window.XMLHttpRequest)
request = new XMLHttpRequest();
else
request = new ActiveXObject("Microsoft.XMLHTTP");
request.open('GET', 'http://www.mozilla.org', false);
request.send(); // there will be a 'pause' here until the response to come.
// the object request will be actually modified
if (request.status === 404) {
alert("The page you are trying to reach is not available.");
}
-
13plus 1 due to your low reputation. (and the great answer :)) – silver Jul 20 '15 at 06:38
-
12NO NO NO. Please do not link anything with W3C to W3 Schools. They are not affiliated in ANY WAY. – IE5Master Jul 07 '16 at 16:30
-
3Just note that: Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/. – Aus Sep 27 '16 at 14:58
-
1Upvote so he can have enough reputation to comment on Derek 朕會功夫's answer ! (Good answer, don't let anything stop you bro) – KADEM Mohammed Jun 04 '18 at 08:41
-
I'm surprised people really upvoted this. Please don't use this solution. That synchronous/ "pause" is not considered best-practice at all. Try to test this with throttle set to slow 3G connection in browser debug and you will notice the user can't do anything to the page while the "pause" happens. Even the Jquery solution in other answer is better practice with asynchronous approach (take it for an example even if you dont want to include jquery) – izzulmakin Dec 15 '20 at 05:38
Use a XHR and see if it responds you a 404 or not.
var request = new XMLHttpRequest();
request.open('GET', 'http://www.mozilla.org', true);
request.onreadystatechange = function(){
if (request.readyState === 4){
if (request.status === 404) {
alert("Oh no, it does not exist!");
}
}
};
request.send();
But notice that it will only work on the same origin. For another host, you will have to use a server-side language to do that, which you will have to figure it out by yourself.

- 1
- 1

- 92,235
- 44
- 185
- 247
-
1@Mario - Yes, as long as it is in the same origin due to the same-origin-policy. – Derek 朕會功夫 Jun 07 '12 at 21:54
-
-
1
-
Good answer - but the programmer may feel free to allow cross origin requests if required and if they control that resource; making this still a good answer even in that scenario. – Gerard ONeill Feb 25 '21 at 16:22
-
-
Denying load of chrome-extension://bfnaelmomeimhlpmgjnjophhpkkoljpa/icon16.png. Resources must be listed in the web_accessible_resources manifest key in order to be loaded by pages outside the extension – huykon225 Nov 15 '21 at 09:53
I found this worked in my scenario.
The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callback methods introduced in jQuery 1.5 are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.
$.get("urlToCheck.com").done(function () {
alert("success");
}).fail(function () {
alert("failed.");
});

- 322
- 2
- 6
I created this method, it is ideal because it aborts the connection without downloading it in its entirety, ideal for checking if videos or large images exist, decreasing the response time and the need to download the entire file
// if-url-exist.js v1
function ifUrlExist(url, callback) {
let request = new XMLHttpRequest;
request.open('GET', url, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.setRequestHeader('Accept', '*/*');
request.onprogress = function(event) {
let status = event.target.status;
let statusFirstNumber = (status).toString()[0];
switch (statusFirstNumber) {
case '2':
request.abort();
return callback(true);
default:
request.abort();
return callback(false);
};
};
request.send('');
};
Example of use:
ifUrlExist(url, function(exists) {
console.log(exists);
});

- 489
- 4
- 7
You could test the url via AJAX and read the status code - that is if the URL is in the same domain.
If it's a remote domain, you could have a server script on your own domain check out a remote URL.
Using async/await
, this worked for me for opening a new tab; I needed to detect a 404 for the same reason as the OP:
openHelp : async function(iPossiblyBogusURL) {
const defaultURL = `http://guaranteedToWork.xyz`;
const response = await fetch(iPossiblyBogusURL);
if (response.status == 200) {
window.open(iPossiblyBogusURL, `_blank`);
} else if (response.status === 404) {
window.open(defaultURL, `_blank`);
}
},

- 582
- 5
- 15
You can try and do a simple GET on the page, if you get a 200 back it means the page exists. Try this (using jQuery), the function is the success callback function on a successful page load. Note this will only work on sites within your domain to prevent XSS. Other domains will have to be handled server side
$.get(
yourURL,
function(data, textStatus, jqXHR) {
//load the iframe here...
}
);

- 10,833
- 7
- 38
- 58
-
This question isn't tagged "jquery", I don't think that people coming here are looking for a solution using this library. – gouessej Sep 22 '21 at 14:42
There is no need to make a separate HTTP request to check beforehand.
You could switch the logic around: only display the iframe if it has been loaded successfully. For this purpose, you can attach an onload
event listener to the iframe.
See this related question for details: Capture iframe load complete event

- 7,541
- 3
- 32
- 42