如果在本地(而不是从Web服务器)加载包含Javascript代码的.htm
文件,如何使用Javascript检查本地磁盘上是否存在.htm
文件?
答案 0 :(得分:5)
此解决方案适用于IE和FF的大多数版本。从本地磁盘运行时,无法在Chrome上运行。
我在同步模式下使用XHR和旧的IE ActiveX控件。您可以轻松地将其转换为使用onreadystatechange回调运行异步。
在您自己的Javascript代码中,只需调用IsDocumentAvailable(“otherfile.htm”)即可设置。
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;
}
答案 1 :(得分:2)
答案 2 :(得分:0)
假设htm文件位于同一个域中,您可以执行以下操作:
function UrlExists(url) {
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
return http.status!=404;
}
由于域安全限制,这在多个浏览器(例如Chrome)上的本地文件系统上无效。