I have tried different approaches to read a text file from the local file system in JavaScript and display the content of the file in alert() but all to no avail.
Approach 1
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.response;
document.getElementById("content").innerText = allText;
alert(allText);
}
} else {
alert("Can't read the file");
}
}
rawFile.send(null);
}
readTextFile("FormulaQuestion.txt");
The FormulaQuestion.txt file is in the same directory with the html file, this approach shows an empty alert window on the browser
Approach 2 using fetch method
fetch('FormulaQuestion.txt')
.then(response => response.text())
.then((data) => {
alert(data);
})
This doesn't show anything
Approach 3 using JQuery
$.get('FormulaQuestion.txt', function (data) {
alert(data)
}, 'text');
This doesn't work either.
I am building a desktop application that uses a web browser control to load html file which is embedded into the application. The application reads the string from sqlite database and save it in the FormulaQuestion.txt file, then refreshes the WebControl component which reloads the html file.
Now when the html file is reloaded, the JavaScript should read the text file and display it on alert() which once the alert is able to display the file content, i will then set it to a paragraph and remove the alert().
Please someone should help me out.
Browsers by design do not allow access to the file system for JavaScript, as allowing such access would be a serious security concern.
To provide the FormulaQuestion.txt file to your script you will need to host the file on a server and request it via a HTTP request (like with your fetch). The key thing here is that a server is needed to actually transmit the file over the HTTP protocol to your script.
If working locally, there are many options for running a local server.
The npm serve module,
Wamp
Apache
You may also want to try out some free tier services like Vercel or Netlify. Both I believe allow you to just drag/drop a file and it will host it for you.
Related
Instead of using jQuery here I am trying to use Javascript to load several .php files to
display data from the database according to the user's input. Below is an example of how my functions are like (and most of which are similar):
let userinput = document.getElementById("input");
button_1.onclick = function()
{
let xhr = new XMLHttpRequest();
xhr.open("GET", "ajax/highscore.php?q="+userinput.value, true);
// send the "username" to $_POST['q'] defined in "highscore.php"
// and then display the data according to the user's input
xhr.addEventListener("load", (event) =>
{
if (xhr.readyState == 4 && xhr.status == 200) { // display data accordingly }
});
xhr.send();
}
and below is a screenshot of the index in the server. "sample.html" is the page for displaying all the data.
However, when inspecting "sample.html", I cannot see the "ajax" folder loaded, nor any other .php files even when I changed the path "ajax/( ).php" to "( ).php". Could anyone explain why this will happen? (In the second screenshot because the parent folder contain my server's name so I covered it)
The browser dev tools (the inspect method you are using) do not list files in your server folder. It only displays files used to load your sample.html page, like CSS, JS files directly referenced (with <script> tags, and so on), etc.
Your .php files might still work, if your javascript ajax method calls them accordingly and they are reachable by the user's browser.
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?
No - that's an attempt at a security through obscurity model and not a very obscure one. You can't trust the client or hide information from it. If a script can see it, a malicious or inquisitive user can see it too.
The solution is to expose on your server what someone should be able to see and no more. If the content is private for specific users, you'll need to setup some kind of login and authentication when they request it.
Issue
Unable to load local JSON file in a javascript file which is spun up with node.
Details
The question is straight forward but I am not serving the javascript file in a browser. I have a javascript file which has the logic, I then spin it up with:
node main.js
I googled a few solutions, they recommend using JQuery or XMLHttpRequest but they appear to be running into issues related to the fact i am no serving this in a browser.
Project Background
I am using a raspberry PI to get data from an IR Temperature Sensor. I am using python to get calculate the voltage, convert to celsius, then export that as a JSON file. I then plan to load this file into my javascript file which then configures angular fire Database and pushes this data.
I have a front-end application that will then pull this down and display the end data to the user.
If I go with the JQuery:
Option 1
sample:
$.getJSON("test.json", function(json) {
console.log(json); // this will show the info it in firebug console
});
Error
$.getJSON is not a function even though I am requiring jQuery.
Option 2
If I go with pure javascript, I see
sample
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'my_data.json', true); // Replace 'my_data' with the path to your file
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
// Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
callback(xobj.responseText);
}
};
xobj.send(null);
}
Error
xobj.overrideMimeType is not a function
TL/DR
How do I load a local JSON file into a javascript file that is not loaded into a browser but instead spun up with node,
node main.js
Node.js can load JSON files through require. See the documentation here: https://nodejs.org/api/modules.html#modules_all_together
If filename begins with './' or '/' or '../'
If filename.json is a file, parse filename.json to a JavaScript Object. STOP
Most likely what you want is const json = require('./test.json') assuming test.json is in the same directory as the code requiring it. Remember that require parses the JSON, so json in the example is a JavaScript Object.
I have a button in in view page. On clicking the button an function gets called.In that function am calling another function with location of file as parameter.In the second function i need to read the file specified in the location passed and show the contents in console.What i already tries is below
ReadFile : function(){
this.ReadTextFile("C:\Users\RFRANCIS\Downloads\Inv00008W.txt");
},
ReadTextFile: function(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);
}
But I am getting Access denied error.Please find me to solve this issue or suggest another method.I am testing this in IE11.
In order to access you local drive you need a valid URL for the file which probably looks more like file:///c:/ than what you have but you have a few overlapping issues here:
The url for a local file must start with file:///
You need to understand about escape characters and slashes in Javascript string literals (you need special syntax to express slashes in javascript)
When you fix these you are still going to get CORS security exceptions because (at least chrome) doesn't perceive local files as one domain. (To resolve this you either need to set you chrome up specially or use a proper localhost http-server on your local machine.
I am working on a simple project which involves loading local .xml file into DOM structure by local .html file. We can assume that .html and .xml file are placed in the same folder on the same computer. Problem is that IE 11 disallows any interaction with local xml file. (SCRIPT5: Access is denied.)
So far i tried this solutions (Solution 1,2 are tested and functional within Mozilla FireFox and Google Chrome, Microsoft Edge has some different problem - see first code snippet):
Synchronous/Asynchronous XMLHttpRequest (async in example)
function loadXMLDoc(doc)
{
try{
xmlhttp = new XMLHttpRequest();
}catch(e){
try {
xmlhttp = new ActiveXObject("MSXML2.XMLHTTP.3.0");
}
catch(e){
try {
xmlhttp = new ActiveXObject("MSXML2.XMLHTTP");
}
catch(e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e) {
alert("XMLHTTP Not Supported On Your Browser");
}
}
}
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200) /*Microsoft edge returns status 0 here */
{
alert(xmlhttp.responseText);
}
};
xmlhttp.open("GET",doc,true);/*IE11 prints "SCRIPT5: Access is denied." into console*/
xmlhttp.send();
}
And JQuery async solution
window.onload = function() {
$.ajax({
url: "output.xml",
aync: true,
success: myHandle,
isLocal:true,
dataType: "xml"
});
}
function myHandle(data) {
alert(data);
}
Third solution consists of simple node.js webserver (see Using node.js as a simple web server)
but this seems to be a too large gun for me.
Also there is a problem that web server has to be start explicitly via cmd / script, but i just want to hit .html and see interpreted xml data.
TL;DR My questions are:
Is there any workaround that makes local .xml files accessible for
IE11?
Why is this "security risk" for IE but not for others?
Note:
Since .xml file can have more Mb, async solutions are prefered for me.
Thank you.
If you're trying to provide the file path as a local path, then it won't work in other browsers as well, using plain javascript, and you may get Cross domain errors. If you have a web server, you can put the file there in the appropriate location, and provide the path as "http://localhost/.../file.xml". This may help.
Well, what I propose as a backup opportunity is to go away a bit from the html + js solution and try XML + XSLT. This should not have any security issues, the only thing that changes for you - you don't need to open index.html but you'll need to open output.xml in your browser.
Also, you would need to add to your XML file the pointer to your XSLT file, see e.g. here how to do that.
Once you loaded your XML and processed it with XSLT you have the same HTML with the same JavaScript, but all data is already rendered. XSLT is quite powerful and I am sure it will fulfill all your requirements