Reputation: 1430
I've read this post: How to read a local text file? but it didn't work in chrome as noted in this comment: This won't work in Chrome (possiblity other browsers) you will get "Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource."
. Also note that I am using a relative path because this was said to work in the comments. Here is the code:
<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);
}
readTextFile("file.txt")
</script>
and here is the error:
Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
I have also attempted to follow other solutions such as using fetch however I get the same error about cross origin requests
after doing some reading on the topic I have come to the conclusion that for security reasons you can't read local files without permission. What I'd like to know is how to write some javascript that will ask for these permissions before attempting to read the file. If you could give some working code (an entire html file like I provided above) as part of your answer that would be preferred. Thanks
Upvotes: 1
Views: 108
Reputation: 84
Are you familiar with Node.js? You are most likely going to need to run your file on a server or on localhost in order to use cross origin requests.
Upvotes: 2