Reputation: 127
I'm developing a firefox plugin for fun, but I ran into an issue. I want to read a text file, but I can't seem to be able to open the file for reading. I'm running this on my computer, no servers involved.
Here's the code I'm using:
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;
var lines=rawFile.responseText.split('\r\n');
var list=[];
for (var line=0; line<lines.length; line++)
{
list.push(lines[line]);
}
console.log(list);
}
}
}
rawFile.send(null);
}
readTextFile('file:///C:/Users/respect/my/privacy/ImgArray.txt');
The script gets as far as rawFile.onreadystatechange =
as far as I can tell after a bit of testing. My path seems to be correct, so what am I doing wrong here?
Upvotes: 1
Views: 1319
Reputation: 1147
change the last line into this
readTextFile('./privacy/ImgArray.txt'); or readTextFile("./privacy/ImgArray.txt"); and make sure your file exist in that path .
good luck
Upvotes: 0
Reputation: 10219
Opening arbitrary files using file://
does not work for security reasons. If you were allowed to read local files off the file system, any plugin or website could try to scan your hard drive and read any contents.
If you host the file on a domain you own with proper cross-origin headers it should work e.g. http://mydomain/myfiles/ImgArray.txt
.
If you want a local file you have to use the HTML5 File API and let the user select which file to give permission to.
Upvotes: 2