Entry
How can client side JavaScript read text files on a web server?
Apr 15th, 2000 09:31
Martin Honnen,
For a cross browser solution consider a Java applet which by the applet
security model is allowed to read from urls on the same server the
applet is loaded from.
JavaScript with NN4 however can directly call into Java to read from
urls on the web server it is loaded from:
function fetchURL(url) {
if ((location.host == '' && url.indexOf(location.protocol) == -1)
||
url.indexOf(location.host) == -1)
{
netscape.security.PrivilegeManager.enablePrivilege
("UniversalConnect");
}
var dest = new java.net.URL(url);
var dis = new java.io.DataInputStream(dest.openStream());
var res = "";
while ((line = dis.readLine()) != null) {
res += line;
res += java.lang.System.getProperty("line.separator");
}
dis.close();
return res;
}
//example call
alert(fetchURL(location.href))
Note that the fetchURL function even allows you to read files from
another server if it is regarded as trusted. Check the entry on trusted
scripts in the browser settings section.
IE5 comes with a built in mechanism to read text files from the server,
it is the so called download behaviour; you include the following with
your html tag:
<html xmlns:msie>
<msie:download id="downloader"
style="behavior:url(#default#download)" />
<HEAD>
Then you have an object with the choosen id e.g.
downloader
with a method
startDownload
which takes a url string as a parameter and a function to call when the
download is finished. Example:
<SCRIPT>
downloader.startDownload('somePage.html', displayData);
function displayData(text) {
alert(text);
}
</SCRIPT>
With IE4 there is a restricted solution to read an HTML file into a
hidden IFRAME and then access the innerHTML of the document body:
http://www.faqts.com/knowledge-base/view.phtml/aid/1272/fid/128/lang/en