Access Local Files with Local Javascript [duplicate] - javascript

This question already has answers here:
Local file access with JavaScript
(14 answers)
Closed 8 years ago.
Based on the other answers on this site, I already feel like I know the answer to this question, but, as it's slightly different, I wanted to ask.
Is it possible to access local files from JavaScript that is running locally on the machine (AKA, my website address will be file:///C:/...)? Or, is this sandboxed as well?
What I am trying to do: I have a standalone computer that I want people to be able to drop in JSON or XML files into a local folder which are read in at the creation of the site and used to generate a single web page. If the JavaScript solution is not possible, can you provide any other suggestions?
Thank you.

A webpage can read any file on the same server as it was loaded from (this is the cross-site policy of JavaScript). That means that the page file:///C:/mywebsite/index.html can read the file file://C:/somedir/somefile.xml. To read this file, either use ajax, load it in an iFrame or load it as a javascript or css file.
Several browsers support custom methods for loading local file (and other interesting things), IE has activeX and Firefox has XPCOM.

According to the Firefox documentation, the following code will work:
var req = new XMLHttpRequest();
req.open('GET', 'file:///home/user/file.json', false);
req.send(null);
if(req.status == 0)
dump(req.responseText);
I seem to recall it only works within the same directory as the HTML page. And I don't know if this will work in other browsers.

This will only work on IE, but if that is not a problem for you, here is some sample code to write to a file:
var fso, s;
fso = new ActiveXObject("Scripting.FileSystemObject");
s = fso.OpenTextFile("c:\\path\\to\\myfile.txt" , 8, 1, -2);
s.writeline("Hello World");
s.Close();
And then to read from it:
f = fso.OpenTextFile(filename, ForReading);
while (!f.AtEndOfStream) {
var r = f.ReadLine();
document.write (r + "<br />");
}
f.Close();
For more information about OpenTextFile, check out: http://msdn.microsoft.com/en-us/library/314cz14s(VS.85).aspx

IF the user grants your webpage permission to access those files, and IF they are located on the same machine as the webpage, then there is nothing preventing you from gaining Read Only access to files on the machine via JavaScript.

If people are to drop a json string in to a folder, you could just have it be a plain text file, then use an AJAX call to the file name, just like you would point it to a php/asp script. I do this all the time for testing of pages before I have the backend done.
I.E. if your page were C:\foo\index.html, you could have them drop to C:\foo\putyourstuff\json.txt here and run an AJAX call "putyourstuffhere/json.txt".

You could read the files using just an Ajax request, as though it was to the server. But you have to know the name of the file, and you can't write files.

If you make an hypertext application page (.hta) instead of an HTML page (.htm/.html), then you have full access to the file system, using the FileSystemObject object.
(Well, limited by the file access of the user account that is running the browser, of course.)

This worked for me in Firefox...
Adapted code from this site: http://www.h-online.com/security/services/Firefox-Mozilla-Demo-Reading-local-files-via-local-HTML-files-761851.html
<HTML>
<BODY onLoad="ReadFileContent()" >
<iframe id="local_file" name="local_file"
src="file:///C:/test.txt"
height=0 width=0>
</iframe>
<script>
function ReadFileContent(){
alert(local_file.document.firstChild.innerHTML);
}
</script>
<h2>Read Local File</h2>
<P>
If a window displays the content of your local file C:\test.txt
the demo worked. If no additional window appears, it failed. You can
close this window now.</p>
</body>
</html>

You should consider some sort of server side scripting language such a PHP, Perl, JSP or some form of SSJS.

Yes, although insecure, you can use:
fopen("c:\\MyFile.txt", 'r');

Related

Executing a JavaScript file directly from the browser

This sounds like a trivia question but I really need to know.
If you put the URL of an HTML file in the Location bar of your browser, it will render that HTML. That's the whole purpose of a browser.
If you give it a JPG, or a SWF, or even PDF, it will do the right things for those datatypes.
But, if you give it the URL of a JavaScript file, it will display the text of that file. What I want is for that file to be executed directly.
Now, I know that if you use the javascript: protocol, it will execute the text of the URL, but that isn't what I need.
I could have the URL point to an HTML file consisting of a single <script> tag that in turn points to the JavaScript file, but for occult reasons of my own, I cannot do that.
If the file at http://example.com/file.js consists entirely of
alert("it ran");
And I put that URL in the Location bar, I want "it ran" to pop up as an alert.
I'm skeptical that this is possible but I'm hoping-against-hope that there is a header or a MIME type or something like that that I can set and miraculously make this happen.
This is not possible. The browser has no idea what context the JavaScript should run in; for example, what are the properties of window? If you assume it can come up with some random defaults, what about the behavior of document? If someone does document.body.innerHTML = "foo" what should happen?
JavaScript, unlike images or HTML pages, is dependent on a context in which it runs. That context could be a HTML page, or it could be a Node server environment, or it could even be Windows Scripting Host. But if you just navigate to a URL, the browser has no idea what context it should run the script in.
As a workaround, perhaps use about:blank as a host page. Then you can insert the script into the document, giving it the appropriate execution context, by pasting the following in your URL bar:
javascript:(function () { var el = document.createElement("script"); el.src = "PUT_URL_HERE"; document.body.appendChild(el); })();
Or you can use RunJS: https://github.com/Dharmoslap/RunJS
Then you will be able to run .js files just with drag&drop.
Not directly, but you could make a simple server-side script, e.g. in PHP. Instead of
http://example.com/file.js
, navigate to:
http://localhost/execute_script.php?url=http://example.com/file.js
Of course, you could smallen this by using RewriteRule in Apache, and/or adding another entry in your hosts file that redirects to 127.0.0.1.
Note that this is not great in terms of security, but if you use it yourself and know what you're downloading, you should be fine.
<html>
<head>
<script>
<? echo file_get_contents($_GET['url']); ?>
</script>
</head>
<body>
</body>
</html>
In the address bar, you simply write
javascript:/some javascript code here/;void(0);
http://www.javascriptkata.com/2007/05/01/execute-javascript-code-directly-in-your-browser/
Use Node.js.
Download and install node.js and create a http/s server and write down what you want to display in browser.
use localhost::portNumber on server as url to run your file.
refer to node js doc - https://nodejs.org/dist/latest-v7.x/docs/api/http.html
Run - http://localhost:3000
sample code below :
var http = require("http");
var server = http.createServer(function(req,res){
res.writeHead(200,{'Content-Type':'text/html'});
res.end("hello user");
}); server.listen(3000);`
you can write your own browser using qt /webkit and do that.
when user enters a js file in url location you can read that file and execute the javascript .
http://code.google.com/apis/v8/get_started.html is another channel.
not sure if it meets ur need.

Generate text/xml-file using javascript/jquery?

I would like to know if there is any way to generate a text/xml file in javascript. I want users to be able to fill out a page form when they are offline, save the data, and then use the saved file at a later point in time. The browser will be IE, most likely IE7.
Thanks
The files should be stored on client filesystems, right?
In general, saving data on client's computer by a web script would be considered a security breach. I would avoid doing so but if it's one of your project requirements, you can give it a try.
Since the target platform would be IE, you can try ActiveX. Example code (not tested):
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fh = fso.CreateTextFile("c:\\path\\file.txt", true);
fh.WriteLine("Some text");
fh.Close();
You might have to use Flash in order to access the user's filesystem to save the file. That is the way most client-side components work if they need to create a file wholly on the client.
Time to learn ActionScript, and say goodbye to iDevices compatibility!

Is it possible to load in a local version of a JavaScript file instead of the server version?

Just had a quick question to throw out and see if there was a solution for this...
Let's pretend I have no access to the server.
I load up a webpage and find out that they have a Javascript file loading from a subfolder (let's say /scripts/js/some.js)
Now, I want to make changes to this file locally and test it against the whole site without downloading the entire site to a local folder.
Does anyone know of a way I can override the loading of that remote js file in favor of a local/edited copy of it?
Try using noscript or adblock to block the server side script from loading. Then use greasemonkey to load your own script.
I actually found a solution for this. Posting details for anyone that comes here looking for it.
Privoxy (www.privoxy.org/) [Free] Allows this for the most part through a redirect. Though Firefox may block the redirect depending on where you put it. This means you most likely will not be able to save the file locally and reference it via file://etc/
( I wish I had a way to tell you how to statically fiddle with JavaScript on web pages you have limited access to... but I have not found it. If an answer comes along I will accept it over this. )
Of course, you have to set up Privoxy, and use it as a local proxy server. It's pretty simple if you only use it temporarily: Just point your browser to proxy 127.0.0.1 on port 8118 with it running.
You have to add a redirect "default action" (Options > Edit Default Actions) to redirect the browser to use your new copy:
{ +redirect{/newLocation/some.js} }
/scripts/js/some.js
If you want a way to use a local file instead of a remote file (in any web browser), I highly recommend Charles Web Proxy. http://www.charlesproxy.com/
In Charles, go to the Tools menu and select Map Local. Add a new mapping by entering the address of the file on the web you would like loaded from your disk.
This technique will for all sorts of files (JavaScript, CSS, SWF). Of course you have the option to temporarily disable this feature, and it will only work while Charles is running. Very handy.
While your solution with proxy is somewhat more permanent, I found that with Fiddler you can do it with almost no configuration:
How to replace Javascript of production website with local Javascript?
In a browser that supports FileReader such as Chrome, yes, in combination with 'eval' to execute arbitrary JS. In your HTML add a button for the user to press:
<form>
<input type="file" name="file"
onchange="loadJS(event.target.files);">
</form>
In your scripts add:
function load() {
var reader = new FileReader();
reader.onload = function(evt) {
eval(evt.target.result);
};
reader.readAsText(files[0]);
}

Retrieve text from external HTML/asp page with JavaScript

I am using an external asp page (On the company's server - not related to me beside the fact that I'm using it for my job).
The asp page has one query in it, I'm writing something in it and it gives me some information.
In the information there is a certain line with constant header (let's assume 'HEADER'), I want to build an HTA that pulls the line that contains 'HEADER' to my HTA and display only this line.
I think that this isn't possible without any server interaction, but I'm asking anyway.
Can someone think of a way doing it?
Thanks,
Rotem
You can use an Ajax request to pull data from that page. The javascript page needs to be on the same server as the page you want to pull data from because of cross site scripting prevention in most browsers. Here is a good place to start: http://www.w3schools.com/ajax/ajax_intro.asp
Ok, I made something with JavaScript, using Telnet.
It isn't working for all sites, when I'll be at work I'll check it, but I think this will do the job.
The code:
<script type="text/javascript">
var WshShell = new ActiveXObject("WScript.Shell");
WshShell.Run("telnet -fc:/telnetlog.txt www.google.com 80"); // This will save me the source file + minor junk!
setTimeout("WshShell.SendKeys('GET / HTTP/1.0~~')",1000); // Enter the command it telnet </script>
Thanks for the brainstorming,
Rotem

Generate some xml in javascript, prompt user to save it

I'd like to make an XML document in JavaScript then have a save dialog appear.
It's OK if they have to click before the save can occur.
It's *not* OK if I *have* to use IE to achieve this (I don't even need to support it at all). However, Windows is a required platform (so Firefox or Chrome are the preferred browsers if I can only do this in one browser).
It's *not* OK if I need a web server. But conversely, I don't want to require the JavaScript to be run on a local file only, i.e. elevated privileges -- if possible. That is, I'd like to to run locally or on a *static* host. But just locally is OK.
It's OK to have to bend over backwards to do this. The file won't be very big, but internet access might either be there, be spotty or just not be a possibility at all -- see (3).
So far the only ideas I have seen are to save the XML to an iframe and save that document -- but it seems that you can only do this in IE? Also, that I could construct a data URI and place that in a link. My fear here is that it will just open the XML file in the window, rather than prompt the user to save it.
I know that if I require the JavaScript to be local, I can raise privileges and just directly save the file (or hopefully cause a save dialog box to appear). However, I'd much prefer a solution where I do not require raised privileges (even a Firefox 3.6 only solution).
I apologize if this offends anyone's sensibilities (for example, not supporting every browser). I basically want to write an offline application and Javascript/HTML/CSS seem to be the best candidate considering the complexity of the requirements and the time available. However, I have this single requirement of being able to save data that must be overcome before I can choose this line of development.
How about this downloadify script?
Which is based on Flash and jQuery, which can prompt you dialog box to save file in your computer.
Downloadify.create('downloadify',{
filename: function(){
return document.getElementById('filename').value;
},
data: function(){
return document.getElementById('data').value;
},
onComplete: function(){
alert('Your File Has Been Saved!');
},
onCancel: function(){
alert('You have cancelled the saving of this file.');
},
onError: function(){
alert('You must put something in the File Contents or there will be nothing to save!');
},
swf: 'media/downloadify.swf',
downloadImage: 'images/download.png',
width: 100,
height: 30,
transparent: true,
append: false
});
Using a base64 encoded data URI, this is possible with only html & js. What you can do is encode the data that you want to save (in your case, a string of XML data) into base64, using a js library like jquery-base64 by carlo. Then put the encoded string into a link, and add your link to the DOM.
Example using the library I mentioned (as well as jquery):
<html>
<head>
<title>Example</title>
</head>
<body>
<script>
//include jquery and jquery-base64 here (or whatever library you want to use)
document.write('click to make save dialog');
</script>
</body>
</html>
...and remember to make the content-type something like application/octet-stream so the browser doesn't try to open it.
Warning: some older IE versions don't support base64, but you said that didn't matter, so this should work fine for you.
Without any more insight into your specific requirements, I would not recommend a pure Javascript/HTML solution. From a user perspective you would probably get the best results writing a native application. However if it will be faster to use Javascript/HTML, I recommend using a local application hosting a lightweight web server to serve up your content. That way you can cleanly handle the file saving server-side while focusing the bulk of your effort on the front-end application.
You can code up a web server in - for example - Python or Ruby using very few lines of code and without 3rd party libraries. For example, see:
Making a simple web server in python
WEBrick - Writing a custom servlet
python-trick-really-little-http-server - This one is really simple, and will easily let you server up all of your HTML/CSS/JS files:
"""
Serves files out of its current directory.
Doesn't handle POST requests.
"""
import SocketServer
import SimpleHTTPServer
PORT = 8080
def move():
""" sample function to be called via a URL"""
return 'hi'
class CustomHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_GET(self):
#Sample values in self for URL: http://localhost:8080/jsxmlrpc-0.3/
#self.path '/jsxmlrpc-0.3/'
#self.raw_requestline 'GET /jsxmlrpc-0.3/ HTTP/1.1rn'
#self.client_address ('127.0.0.1', 3727)
if self.path=='/move':
#This URL will trigger our sample function and send what it returns back to the browser
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
self.wfile.write(move()) #call sample function here
return
else:
#serve files, and directory listings by following self.path from
#current working directory
SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
httpd = SocketServer.ThreadingTCPServer(('localhost', PORT),CustomHandler)
print "serving at port", PORT
httpd.serve_forever()
Finally - Depending on who will be using your application, you also have the option of compiling a Python program into a Frozen Binary so the end user does not have to have Python installed on their machine.
Javascript is not allowed to write to a local machine. Your question is similar to this one.
I suggest creating a simple desktop app.
Is localhost PHP server ok? Web traditionally can't save to hard drive because of security concerns. PHP can push files though it requires a server.
Print to PDF plugins are available for available for all browsers. Install once, print to PDF forever. Then, you can use a javascript or Flash to call a Print function.
Also, if you are developing for an environment where internet access is spotty, conwider using VB.NET or some other desktop language.
EDIT:
You can use the browser's Print function.
Are you looking for something like this?
If PHP is ok, if would be much easier.
With IE you could use document.execCommand, but I note that IE is not an option.
Here's something that looks like it might help, although it will not prompt with SaveAs dialog, https://developer.mozilla.org/en/Code_snippets/File_I%2F%2FOL.
One simple but odd way to do this that doesn't require any Flash is to create an <a/> with a data URI for its href. This even has pretty good cross-browser support, although for IE it must be at least version 8 and the URI must be < 32k. It looks like someone else on SO has more to say on the topic.
Why not use a hybrid flash for client and some server solution server-side. Most people have flash so you can default to client side to conserve resources on the server.

Categories