简体   繁体   中英

Check if .htm file exists on local disk using Javascript

我如何检查是否一个.htm文件中使用了JavaScript的本地磁盘上存在.htm包含Javascript代码文件(从网络服务器并不)本地加载?

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;
    }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM