Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
39
rated 0 times [  40] [ 1]  / answers: 1 / hits: 82601  / 13 Years ago, sat, june 18, 2011, 12:00:00

I would like to write a small html file that would run locally and manipulate a small text file on my computer. My requirements are:




  • Text file sits in a directory on my computer (test.txt)

  • Html file is in the same directory as the text file (test.html)

  • I would like to use javascript in the html to read and write the text file.



Is this possible at all? If yes, how do I read and write my text file using javascript?


More From » html

 Answers
2

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.


[#91643] Thursday, June 16, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
leog

Total Points: 225
Total Questions: 113
Total Answers: 118

Location: Oman
Member since Wed, Apr 12, 2023
1 Year ago
;