[英]Is it possible to check if a file exists on disk using Javascript (not running in a browser)?
[英]Check if .htm file exists on local disk using Javascript
我如何檢查是否一個.htm
文件中使用了JavaScript的本地磁盤上存在.htm
包含Javascript代碼文件(從網絡服務器並不)本地加載?
該解決方案適用於大多數版本的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;
}
假設htm文件位於同一域中,則可以執行以下操作:
function UrlExists(url) {
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
return http.status!=404;
}
由於域安全性限制,這在某些瀏覽器(例如Chrome)上的本地文件系統上將不起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.