The following code, located inside of an HTML file, reads the contents of a local .txt file into a Javascript string variable:
<script>
window.onload=function(){
var allText;
readTextFile("/files/Textfile.txt");
function readTextFile(file)
// https://stackoverflow.com/a/14446538/8840617
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
allText = rawFile.responseText;
}
}
}
rawFile.send(null);
}
}
</script>
The JavaScript code continues to parse this text to extract a specific substring from allText
, and then finally this substring is shown to the user in the HTML.
The problem is that any visitor can find the text file's path by clicking "View Source" in their browser, and then they can navigate to the text file in their browser to see the file in full.
I do not want anyone to be able to see the complete contents of this text file.
So, is it possible to prevent visitors from viewing the .txt file, while still allowing my .html webpage to import the data from the .txt file as a string?
If it is not possible, how should I accomplish this effect, exactly?