Entry
How can I capture 404 errors from inside an <IFRAME> using javaScript?
May 6th, 2002 15:24
Jean-Bernard Valentaten, Marius Agricola,
There might be a possibility.
You say you're using an <iframe>. Since <iframes> are embedded in a
regular document, only them need to be reloaded, not the whole
document, so we can have a routine checking the <iframe> on a regular
basis, by using setTimeout(). It might look like this:
var timeOut;
function checkIFrame(newURL)
{
var content = document.getElementById('myIFrame').document.innerHTML;
var errorHTML = '';
//you need to insert the standard "error404" html-code here!!
if (content != null)
{
content = content.toLower();
errorHTML = errorHTML.toLower();
if ((content.indexOf(errorHTML) != -1) ||
(errorHTML.indexOf(content) != -1))
{
//if content is a sub-string of errorHTML or
//the other way around, then the error occured
//so we need to do something (e.g. load another page)
document.getElementById('myIFrame').location.href = newURL;
timeOut = null;
}
else if (content.indexOf('</html>') <> -1)
{
//if '</html>' isn't in the content, the probability
//is high, that the document hasn't comleted loading.
//so we'll check again in 2 seconds
var functionCall = 'checkIFrame(' + newURL + ')';
timeOut = setTimeOut(functionCall, 2000);
}
}
else
{
var functionCall = 'checkIFrame(' + newURL + ')';
timeOut = setTimeOut(functionCall, 2000);
}
}
This will make sure that if a 404-error occures, another page is loaded.
But this timeout needs to be triggered, so the page contained in the
<iframe> needs to start the timeout when it is unloaded, so you'll need
to make sure that the onUnload handler of the document within the
<iframe> looks like this:
<body ... onUnload="parent.checkIFrame('www.some-url.tld');">
Instead of "www.some-url.tld" you write the URL of page the should be
loaded if an error occurs.
I'm fully aware that this code is not compatible with NN4.x, but I'm
also sure that none of you will have difficulties to fine tune the code
so that it runs in that environment.
HTH,
Jean