2

How can I check if a .htm file exists on local disk using Javascript when the .htm file that contains the Javascript code is loaded locally (not from a web server)?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Cornel
  • 4,652
  • 15
  • 48
  • 57

2 Answers2

5

This solution works on most all versions of IE and FF. Doesn't work on Chrome when running from local disk.

I'm using XHR and old IE ActiveX control in synchronous mode. You can easily convert it to run async with the onreadystatechange callback.

In your own Javascript code, just call IsDocumentAvailable("otherfile.htm") and you should be set.

    function IsDocumentAvailable(url) {

        var fSuccess = false;
        var client = null;

        // XHR is supported by most browsers.
        // IE 9 supports it (maybe IE8 and earlier) off webserver
        // IE running pages off of disk disallows XHR unless security zones are set appropriately. Throws a security exception.
        // Workaround is to use old ActiveX control on IE (especially for older versions of IE that don't support XHR)

        // FireFox 4 supports XHR (and likely v3 as well) on web and from local disk

        // Works on Chrome, but Chrome doesn't seem to allow XHR from local disk. (Throws a security exception) No workaround known.

        try {
            client = new XMLHttpRequest();
            client.open("GET", url, false);
            client.send();
        }
        catch (err) {
            client = null;
        }

        // Try the ActiveX control if available
        if (client === null) {
            try {
                client = new ActiveXObject("Microsoft.XMLHTTP");
                client.open("GET", url, false);
                client.send();
            }
            catch (err) {
                // Giving up, nothing we can do
                client = null;
            }
        }

        fSuccess = Boolean(client && client.responseText);

        return fSuccess;
    }
selbie
  • 100,020
  • 15
  • 103
  • 173
  • I had only to modify the fSuccess assignment to: fSuccess = Boolean(client && client.responseText && client.status != 404); – Cornel Mar 02 '11 at 08:15
  • Cool. What is client.responseText when status is 404 off the filesystem? Depending on different browsers and depending whether the content is local or on a webserver, you may get back "0" or "200" for success. Test the true and false case with different browsers. – selbie Mar 02 '11 at 08:41
  • I don't know why this solution has to be so long, but it does work great! Thanks! – dezman May 14 '13 at 21:02
0

Assuming the htm file is on the same domain, you can do this:

function UrlExists(url) {
  var http = new XMLHttpRequest();
  http.open('HEAD', url, false);
  http.send();
  return http.status!=404;
}

This will not work on the local file system on several browsers, such as Chrome, because of domain security restrictions.

Peter Olson
  • 139,199
  • 49
  • 202
  • 242