Forum Moderators: open
I'm in the middle of coding together a session window that pops up. Problem is, if I reload the window and the target no longer is there for some reason or another (like someone just pulled the network cable), I get an ugly 404 error page.
Is there some way to check if the window it's about to (re)load is available, and if so, display a message saying "Connected"? Or is this outside the scope of JavaScript?
Thanks,
- Wert
If the resource is an image, you're OK. If an image isn't available then the image element will produce an error event. So all you need is a function to handle the responses, and these assignments:
myImage.onload = function(){ resourceFound(true) }
myImage.onerror = function(){ resourceFound(false) }
So, if your are after a page file, you could test for one of the images contained in the page if there are any (but that doesn't mean that the file itself is available )
Otherwise, have a hidden iframe. Load the resource into that. Then you test to see if it's window.location.href property matches the one you requested. This is based on the assumption that if it hasn't loaded the window will be on the browser' (or the site's) 404 error page.
The problem is that you have to wait until the iframe has loaded to be able to test.
- inconvenient:
If the resource is under your control, you can have a script in the resource page that, onload, calls a function on your main page.
- dodgy:
Set a timer and hope the page has turned up by the time it fires.
- probably works:
Set an interval timer, with your test in a try - catch block. The interval is cancelled when you get a hit.
The whole iframe thing feels a little hacky, but the only other option that I can think of - which is more 'official' - is to use an XMLHTTP request, and query the response header. This can be done via JavaScript in Mozilla (and probably others), and via JavaScript & ActiveX in IE. IE has the additional option of the Download object (within the same domain). If you don't like iframes, search under those terms.
<script>test1 = imageAvailable("something_I_just_made_up.jpg",getResponse)
function imageAvailable(url,responseFn)
{
var test = new Image()
test.onerror = function(){responseFn(this,false)}
test.onload = function(){responseFn(this,true)}
test.src = url
return test
}
function getResponse(image,available)
{
image.available = available // gives property to image for testing later
alert(available) // or do something now
}
</script>
..but it only tests whether the image is available at that URL.
You can make any further assumptions at your peril!
But if you use anything that isn't an image as an image .src, the image will fire an error.
You could use an
<object data="url" onerror="blah()">
But it doesn't support an onload handler (mine doesn't), thus the logic is incomplete.
I can't get it to change it's data value dynamically either - even though it's supposed to be possible.