11

I have some JavaScript code loaded from a local HTML file (without going through a webserver).. i.e., opened using file://

Is there a way the JavaScript code in this file can be used to write to a local file?

I know that cross-site restrictions do not allow lot of things in JavaScript, but this is not cross-site, so it should be allowed in theory.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jus12
  • 17,824
  • 28
  • 99
  • 157
  • possible duplicate of [Self modifying html-JavaScript file](http://stackoverflow.com/questions/3854059/self-modifying-html-javascript-file) – Joachim Breitner Oct 20 '13 at 17:07

3 Answers3

11

There's a jQuery plugin jQuery.twFile that allows you to read and write to a local file.

Diogo Cardoso
  • 21,637
  • 26
  • 100
  • 138
4

In case of Internet Explorer you can use ActiveX.

<html>
    <head>
        <script type="text/javaScript">
            function WriteToFile()
            {
               var fso  = new ActiveXObject("Scripting.FileSystemObject");
               var txtFile = fso.CreateTextFile("c:\\TestFile.txt", true);
               txtFile.WriteLine("This is a test");
               txtFile.Close();
            }
        </script>
    </head>

    <body>
        <p>
            <script type="text/javaScript">  WriteToFile(); </script>
        </p>
    </body>
</html>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ashwin Krishnamurthy
  • 3,750
  • 3
  • 27
  • 49
0

There's no native API* for File System access in browsers. You need that first!

For example, in Internet Explorer, there's an ActiveX object for it:

var fso = new ActiveXObject("Scripting.FileSystemObject");

...but it requires the user to relax their browser settings. On other browsers, you may be able to use a jar (Java Archive) file.

You could also see what non-browser JavaScript containers offer, e.g. Microsoft HTA files (HTML Application) will support the Windows ActiveX FileSystemObject fine, providing your Virus Checking Software allows HTA files to execute.

Lee Kowalkowski
  • 11,591
  • 3
  • 40
  • 46