How do I access and read a local file from html+javascript page running locally
As is being discussed in Itay Moav's answer, writing to a local file with a local HTML file is perhaps going to be an issue without running in an elevated privilege mode and having additional Javascript capabilities (that allow you to save local files).
However, accessing a local file from an HTML file is entirely possible. Below is some example code.
mytext.txt
My local text file
local.html
<html>
<head>
<base href="file:///C:/path/to/your/folder/"/>
<script>
window.onload = function(){
var iframe = document.createElement('iframe');
iframe.id = 'iframe';
iframe.style.display = 'none';
document.body.appendChild(iframe);
iframe.src = 'mytext.txt';
setTimeout(function(){
var text = document.getElementById('iframe').contentDocument.body.firstChild.innerHTML;
alert(text);
}, 1000);
}
</script>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>
This will make an alert 1 second after the html page loads (to allow the iframe to load first), and will contain the content within the mytext.txt file.
Note, if it's plaintext, Firefox will wrap it with a PRE element, which is why I did firstChild
. Also, note the use of the BASE element, which points to your local directory with your files.
The example given by Jared works fine. However setting an unknown watiting time is not atractive. Instead attach an onload event to the iframe calling a function reading the contents of the text-file an doing whatever as soon as possible.
Here is a revised example:
<html>
<head>
<script>
function readfile() {
alert(document.getElementById('iframe').contentDocument.body.firstChild.innerHTML);
}
</script>
</head>
<body>
<iframe id='iframe' src = 'test.txt' onload='readfile()'> </iframe>
<h1>Hello World!</h1>
</body>
</html>
The file test.txt off course has to exist in the same directory as the above html file itself.
Normally, it is not possible and would be a security issue.
How ever, if you use some plugins (ActiveX, FF extensions etc) they may enable you to do so.
There is also the subject of local storage you can use with the most newer browsers.
From your comments, I am wondering why not using PHP/Ruby any other server side language to do so? They are tailored just for that.