0

I have a small Javascript, which is supposed to read the content of a local text file and display it on the browsers screen. It works on windows 7 with a current firefox, but it does not work on fedroa 20 with a current firefox or chrome. Here is the code:

<h1>View file content</h1>

<script>
function readTextFile(file)
{
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, false);
    rawFile.onreadystatechange = function ()
    {
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status == 0)
            {
                var allText = rawFile.responseText;
                alert(allText);
            }
        }
    }
    rawFile.send(null);
}

function read_status()
{
    readTextFile('file:///tmp/status.txt');
}

</script>

<input id="clickMe" type="button" value="Current status" onclick="read_status(); " />

Why is this? How can I fix it?

Isaac
  • 810
  • 2
  • 13
  • 31
  • 1
    How you get file on Linux. Like that ```file:///tmp/status.txt``` ? – Alex Filatov Feb 04 '15 at 14:02
  • 1
    Just understand that you should not rely on this behavior. I'm surprised Firefox allows this out of the box (or did you change something?) Local file system access is a thing of the past with JavaScript. Use a server-side technology to read the file contents from the file system for you. You can still use AJAX to make a request to the server, it will just be via a URL (e.g. `http://localhost/myapp/pleasegetmefile.php?path=/tmp/statust.txt` -- but even this is dangerous, as you could request sensitive files). – Cᴏʀʏ Feb 04 '15 at 14:02
  • I also wondered if this is maybe a default security setting, which differs from OS to OS. I did not consciously change any settings. The is created by a local script - I wanted it to be very simple. I could implement a small local web server, but that seems overkill for my intention. – Isaac Feb 04 '15 at 14:08
  • You can use object with text data. Here is the [example](http://www.rgagnon.com/jsdetails/js-0102.html) . If you need to serve file from another part of filesystem, so you definitely need server serving needed folder (or single file). – freele Feb 04 '15 at 14:17
  • Can I make the object autoreloading? Idealy it would monitor the file for changes, but also periodic reloading would be fine. – Isaac Feb 04 '15 at 14:30
  • Thanks for your comments and questions - you directed me to my answer. – Isaac Feb 04 '15 at 14:53

1 Answers1

0

So for what I wanted, the answer is really simple, no need for java script, just plain html:

<h1>Status </h1>

<meta http-equiv="refresh" content="1" > 
<object width="100%" height="100%" type="text/plain" data="/tmp/status.txt" border="0" >
Isaac
  • 810
  • 2
  • 13
  • 31