23

I do know that Javascript cannot write data in the filesystem, for security reasons. I have often read that the only way to save data locally with Javascript is cookies or localStorage.

But is it possible, in the very specific case when the file is accessed locally (and not through internet) to write data locally ? (without any server language, and even without any server at all... just local browsing of a HTML file)

For example, would it be possible, by clicking on SAVE here on this page ...

...that the HTML file is overwritten with its new content ? (i.e. the local HTML file should be updated when SAVE is pressed).


enter image description here


Is this possible to SAVE a file thanks to Javascript, when the HTML page is accessed locally?

Note: I want to be able to silently save, not propose a Download/Save dialog box in which the user has to choose where to download, then "Are you sure to want to overwrite" etc.


EDIT : Why this question? I would like to be able to do a HTML/JS notepad that I can run locally without any server (no apache, no php). I need to be able to save easily without having to deal with Dialog Box "Where do you want to download the file?".

Basj
  • 29,668
  • 65
  • 241
  • 451
  • 2
    I believe the only way you can do that is to submit the contents to some server-side processing (e.g. PHP, Python, etc.) and have the local scripts update the file. – Jacob Ewing Nov 27 '14 at 19:56
  • @JacobEwing and without sever-side processing? I mean *local* browsing of the HTML file, i.e. the browser opens c:\myproject\index.html with no Apache server / no PHP server – Basj Nov 27 '14 at 21:32
  • If you execute the script in the browser (even loaded from your local machine), then there is no way to tell it to modify local files (It's the browser that prevents this, not the server). You may be able to execute it with other software, in which case, I don't know what restrictions remain in place. http://stackoverflow.com/questions/2941411/executing-javascript-without-a-browser has a little more information that may help. – Jacob Ewing Nov 27 '14 at 22:14
  • see also [Javascript save data to file system (with user prompt)](http://stackoverflow.com/q/15212240/1176601) or [Javascript: Create and save file](http://stackoverflow.com/q/13405129/1176601) – Aprillion Nov 30 '14 at 00:27
  • you can alter the behavior of the save/open box to just save without asking, or memorize an app to handle a specific mime. or use an HTA file or "node+webkit" to get direct file-system access. – dandavis Dec 03 '14 at 04:14
  • The closest solution to my question seems to be : FileSystem API (see www.html5rocks.com/en/tutorials/file/filesystem/) but unfortunately, it seems to be dead and only Chrome has it... – Basj Dec 03 '14 at 09:59
  • @dandavis what do you mean by HTA or node+webkit ? Do you mean https://github.com/rogerwang/node-webkit ? Then the client needs to have it installed on his machine to be able to use it, right ? (so few users have it) – Basj Dec 03 '14 at 10:00
  • Why don't you do this: when the button is clicked make an ajax request to php and have php store file. Would that accomplish what you are asking? – www139 Dec 03 '14 at 13:59
  • Maybe java applet. Or flash? I haven't ever done flash though. – www139 Dec 03 '14 at 14:00
  • @www139 I have already implemented a solution with ajax (php on server side), it works, but in order to do a light-version (without server) I would like to be able to do it locally without server – Basj Dec 03 '14 at 19:52
  • @Basj: re: node-webkit, it produces something that runs without installing nore-webkit itself on the endpoint. HTA is ready to ship for windows, and you can use FSO to read/write files, as long as the file has an tag. there's also chrome packaged apps and firefox apps. and cordova. – dandavis Dec 06 '14 at 00:04
  • what is your ultimate goal? – www139 Dec 06 '14 at 15:41
  • @www139 : to be able to do a HTML/JS notepad that I can run locally without any server (no apache, no php). I need to be able to save easily without having to deal with Dialog Box "Where do you want to download the file?" – Basj Dec 06 '14 at 16:02
  • You might want to post that in your question. – www139 Dec 06 '14 at 16:10
  • @www139 I added that at the end of question – Basj Dec 06 '14 at 16:20
  • Have you considered using vbscript, i beleive if you use it in a HTA you can access the file system – Michael Smith Dec 06 '14 at 21:28

10 Answers10

25

You can just use the Blob function:

function save() {
  var htmlContent = ["your-content-here"];
  var bl = new Blob(htmlContent, {type: "text/html"});
  var a = document.createElement("a");
  a.href = URL.createObjectURL(bl);
  a.download = "your-download-name-here.html";
  a.hidden = true;
  document.body.appendChild(a);
  a.innerHTML = "something random - nobody will see this, it doesn't matter what you put here";
  a.click();
}

and your file will save.

Awesomeness01
  • 2,013
  • 1
  • 15
  • 14
7

The canonical answer, from the W3C File API Standard:

User agents should provide an API exposed to script that exposes the features above. The user is notified by UI anytime interaction with the file system takes place, giving the user full ability to cancel or abort the transaction. The user is notified of any file selections, and can cancel these. No invocations to these APIs occur silently without user intervention.

Basically, because of security settings, any time you download a file, the browser will make sure the user actually wants to save the file. Browsers don't really differentiate JavaScript on your computer and JavaScript from a web server. The only difference is how the browser accesses the file, so storing the page locally will not make a difference.

Workarounds: However, you could just store the innerHTML of the <div> in a cookie. When the user gets back, you can load it back from the cookie. Although it isn't exactly saving the file to the user's computer, it should have the same effect as overwriting the file. When the user gets back, they will see what they entered the last time. The disadvantage is that, if the user clears their website data, their information will be lost. Since ignoring a user's request to clear local storage is also a security problem, there really is no way around it.

However, you could also do the following:

  • Use a Java applet
  • Use some other kind of applet
  • Create a desktop (non-Web based) application
  • Just remember to save the file when you clear your website data. You can create an alert that pops up and reminds you, or even opens the save window for you, when you exit the page.

Using cookies: You can use JavaScript cookies on a local page. Just put this in a file and open it in your browser:

<!DOCTYPE html>
<html>

<head>
</head>

<body>
  <p id="timesVisited"></p>
  <script type="text/javascript">
    var timesVisited = parseInt(document.cookie.split("=")[1]);
    if (isNaN(timesVisited)) timesVisited = 0;
    timesVisited++;
    document.cookie = "timesVisited=" + timesVisited;
    document.getElementById("timesVisited").innerHTML = "You ran this snippet " + timesVisited + " times.";
  </script>
</body>

</html>
James Westman
  • 2,468
  • 1
  • 14
  • 19
  • Ok, thanks, that's what I thought (impossible because of security reasons). If it was possible, I would have made for personal use a simple local notepad in HTML : http://gget.it/59b78rl1/NFBF33C.HTML (of course with some more features, thanks to Javascript). Since it's impossible to SAVE in one click, this project is simply impossible :( – Basj Nov 30 '14 at 21:53
  • @Basj You could still achieve the same effect with cookies, though. You would just have to be careful not to clear its web data, or you would lose the notes. There may also be a size limit, but it probably isn't much of a problem for a simple notepad. – James Westman Nov 30 '14 at 21:57
  • @Basj You could also use local storage. (much more space available) – James Westman Nov 30 '14 at 22:01
  • Up to now, I use `localStorage` indeed. But the fact of loosing all my data, and having to remember to export the notepad (with some Download file feature) if I clean the history makes it practically uninteresting and useless... unfortunately... – Basj Nov 30 '14 at 22:06
  • @Basj There are plenty of other options, I will add them to my answer. – James Westman Nov 30 '14 at 22:09
  • Yes @kittycat3141, I want to add my own specific functionality, see my project here http://bigpicture.bi/demo . It is fully working as an online-service (with server side language of course, etc.), but I wanted to try to release it as well as a 100% offline tool : that's why I would need to be able to "SAVE" locally. Any idea ? – Basj Nov 30 '14 at 22:43
  • @Basj If you want to create an offline tool as well, you might want to consider a Java app or something. Plus, this way you can put images and other resources in the same file. ZIP files and stuff are a bit messy for users to deal with. – James Westman Nov 30 '14 at 22:48
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/65917/discussion-between-basj-and-kittycat3141). – Basj Nov 30 '14 at 22:48
  • you can't use cookies or localStorage from a local html page viewed in any common (and unmodified) browser... – dandavis Dec 06 '14 at 00:01
  • @Basj I added a canonical answer (so no, it definitely is not possible with pure JavaScript) – James Westman Dec 06 '14 at 14:36
  • OK OK, i take back my comment, things have changed recently. Just goes to show that web "knowledge" is transient and fading. It pays to keep up and i try, but this update slipped past my attention's goalie. tested in FF and CH, and it works on current versions of both. i am not crazy: https://bugzilla.mozilla.org/show_bug.cgi?id=507361 – dandavis Dec 06 '14 at 23:27
3

Yes, it's possible.

In your example, you are already using ContentEditable and most of tutorials for that attribute have some sort of localStrorage example, ie. http://www.html5tuts.co.uk/demos/localstorage/

On page load, script should check localStorage for data and if true, populate element. Any changes in content could be saved in localStorage when clicking save button (or automatically, in linked example, using blur and focus). Additionally you can use this snippet to check weather user is online or offline and based on state modify your logic:

// check if online/offline
// http://www.kirupa.com/html5/check_if_internet_connection_exists_in_javascript.htm
function doesConnectionExist() {
    var xhr = new XMLHttpRequest();
    var file = "http://www.yoursite.com/somefile.png";
    var randomNum = Math.round(Math.random() * 10000);

    xhr.open('HEAD', file + "?rand=" + randomNum, false);

    try {
        xhr.send();

        if (xhr.status >= 200 && xhr.status < 304) {
            return true;
        } else {
            return false;
        }
    } catch (e) {
        return false;
    }
}

EDIT: More advance version of localStorage is Mozilla localForage which allows storing other types of data besides strings.

Teo Dragovic
  • 3,340
  • 18
  • 33
  • I already tested with `localStorage` but modifications are lost when you clear browser history... So it's not a real solution for the purpose of doing a HTML/JS notepad that I can run locally without any server (no apache, no php). – Basj Dec 06 '14 at 16:21
  • @Basj Ok, I now see your comments on kittycat3141 answer. As explained there, any browser storage technique (cookies, localStorage or appcache) will work offline but won't persis if user decides to clear cache and browsing data. Maybe you should consider integrating 3rd party storage service into your app and use it to store data files? Both Dropbox (https://www.dropbox.com/developers/dropins ) and Google Drive (https://developers.google.com/drive/web/) have pretty nice API you could use. – Teo Dragovic Dec 06 '14 at 17:08
3

You could save files, and make it persistent using the FileSystem-API and webkit. You would have to use a chrome browser and it is not a standards technology but I think it does exactly what you want it to do. Here is a great tutorial to show how to do just that http://www.noupe.com/design/html5-filesystem-api-create-files-store-locally-using-javascript-webkit.html

And to show that its on topic it starts off showing you how to make the file save persistent...

window.webkitRequestFileSystem(window.PERSISTENT , 1024*1024, SaveDatFileBro);
RadleyMith
  • 1,203
  • 10
  • 17
1

Convert your HTML content to a data uri string, and set as href attribute of an anchor element. Don't forget to specify a filename as download attribute.

Here's a simple example:

<a>click to download</a>
<script>
    var anchor = document.querySelector('a');
    anchor.setAttribute('download', 'example.html');
    anchor.setAttribute('href', 'data:text/html;charset=UTF-8,<p>asdf</p>');
</script>

Just try it in your browser, no server required.

Leo
  • 11,955
  • 4
  • 37
  • 58
  • Thanks @LeoDeng, but I want to be able to silently save, not propose a Download dialog box in which the user has to choose where to download. Any other idea? – Basj Nov 30 '14 at 09:19
  • That depends on user's browser settings. If you are going to bypass it, so far as I know it's not possible. – Leo Nov 30 '14 at 10:51
  • 1
    Just solved a minor problem with encoding, so it is worth mentioning here. just before html in data url, add `escape('\xEF\xBB\xBF')`, so it really becomes UTF-8, and language specific characters (Turkish in my case) will display ok. – Erdogan Kurtur Aug 27 '15 at 08:36
1

Have a look into this :) Download File Using Javascript/jQuery there should be everything you need. If you still need help or it's not the solution you need, tell me ;)

Community
  • 1
  • 1
  • Thanks, but it's not exactly what I need. I was looking for something *without* having a Download dialog box being displayed. For the specific reason, see my last comments on kittycat3141's answer. – Basj Nov 30 '14 at 22:46
1

I think it's important to clarify the difference between server and client in this context.

Client/server is a program relationship in which one program (the client) requests a service or resource from another program (the server).

Source: http://searchnetworking.techtarget.com/definition/client-server

I'm not sure you'll find too many advanced applications that don't have at least one server/client relationship. It is somewhat misleading to ask to achieve this without any server, because any time your program speaks to another program, it is a client/server relationship, with the requester being the client and the response coming from the server. This is even if you are working locally. When you want to do something outside of the scope of the browser, you need a hook in a server.

Now, that does not mean you can't achieve this without a server-side specific language. For example, this solution uses NodeJS for the server. WinJS has WinJS.xhr, which uses XmlHttpRequest to serve data to the server.

AJAX seeks to offer the same sort of functions. The point here is that whether you have a program or there is some sort of hook pre-built, when you issue a command like "save file" and the file actually gets saved, there is a program on the other side that is parsing it, whether it's a server-side language or something else, meaning you can't possibly have something like this function without a server to receive the request.

Community
  • 1
  • 1
smcjones
  • 4,921
  • 1
  • 20
  • 36
1

Just use https://github.com/firebase/firepadSee it in action
This doesn’t need a server on your computer, it will reach out and save the data remotely.

Kirk Strobeck
  • 15,873
  • 14
  • 70
  • 107
0

Yes, it is possible. Proof by example:

TiddlyFox: allows modification of local files via an add-on. (source code) (extension page):

TiddlyFox is an extension for Mozilla Firefox that enables TiddlyWiki to save changes directly to the file system.

Todo.html: An HTML file that saves edits to itself. Currently, it only works in Internet Explorer and you have to confirm some security dialogs when first opening the file. (source code) (functional demo).

Steps to confirm todo.html actually saves changes to itself locally:

  1. Save todo.html to local harddrive
  2. Open with Internet Explorer. Accept all the security dialogs.
  3. Type command todo add TEST (todo.html emulates the command-line interface of todo.txt-CLI)
  4. Inspect todo.html file for addition of 'TEST'

Caveats: there is no cross-platform method. I'm not sure how much longer these methods will exist. When I first started my todo.html project, there was a jQuery plugin called twFile that allowed cross-browser loading/saving of local files using four different methods (ActiveX, Mozilla XUL, Java applet, Java Live Connect). Except for ActiveX, browsers have disallowed all these methods due to security concerns.

Leftium
  • 10,906
  • 6
  • 51
  • 75
0

Use jsPDF -> https://github.com/MrRio/jsPDF

<div id="content">
     <h3>Hello, this is a H3 tag</h3>
    <p>a pararaph</p>
</div>
<div id="editor"></div>
<button id="cmd">generate PDF</button>

Javascript

  var doc = new jsPDF();
  var specialElementHandlers = {
      '#editor': function (element, renderer) {
          return true;
      }
  };

  $('#cmd').click(function () {
      doc.fromHTML($('#content').html(), 15, 15, {
          'width': 170,
              'elementHandlers': specialElementHandlers
      });
      doc.save('sample-file.pdf');
  });
Brayan Pastor
  • 606
  • 5
  • 11