3

I'm working on a Chrome extension and I want to take data from text files that will be in the same directory as the Javascript files with the functionality (that is, read the text files in as strings and use those for analysis of some kind). I'm pretty new to Javascript, so I've been trying to figure out how to do this--it seems that FileReader won't work since the user isn't uploading the files I'm using, and I'm not sure how XML HTTPRequest would be useful in this situation. Thank you!

tldr; I want to read text files in the same directory as a Javascript file in as strings.

update: The file is not a file from the user's file system, but one that's packed with the extension! So the folder that contains the HTML file and the Javascript file will also contain the text files.

a girl.
  • 31
  • 1
  • 3
  • Try this https://stackoverflow.com/questions/14446447/how-to-read-a-local-text-file – dev_khan Jan 04 '18 at 07:15
  • To read a file that is in the Chrome extension's package directory, this answer should work: https://stackoverflow.com/a/37674803/3345375 – jkdev Nov 23 '21 at 18:58

3 Answers3

2

Someone correct me if I'm wrong but as far as I know this is not possible in JavaScript due to security concerns.

If it were, a web page could grab any file on your file system without your consent or without you knowing. This is a major security concern so I dont believe it is possible.

A user must be given the option to choose a file from their file system knowingly.

vinay yadav
  • 106
  • 6
  • 2
    Not a file from the user's file system, but one that's packed with the extension! So the folder that contains the HTML file and the Javascript file will also contain the text files. – a girl. Jan 04 '18 at 06:29
1

You can try:

function readTextFile(file)
{
   var rawFile = new XMLHttpRequest();
   rawFile.open("GET", file, false);
   rawFile.onreadystatechange = function ()
    {       
         var allText = rawFile.responseText;
            alert(allText);

    }

 rawFile.send(null);
}

And specify file:// in the same directory as a Javascript file

Dylan Breugne
  • 455
  • 4
  • 7
0

Due to browser security standard you cant access any file from your (HDD) at all.

Please try using this chrome API https://developer.chrome.com/apps/app_storage#filesystem-manifest

Pankaj Rupapara
  • 752
  • 4
  • 9