Can I write files with HTML5/JS?

Assuming your end goal is to let the user save your file somewhere where they will find it, as when right-clicking a link and choosing “Save As…”, there isn’t wide browser coverage for those APIs yet, likely due to security considerations.

What you can do, however – APIs or not – is cheesing it with a link to a data: uri with a download attribute specifying your suggested filename. For instance:

<a id="save" download="earth.txt" href="data:text/plain,mostly harmless&#10;">Save</a>

When clicked, at least in Chrome, this will save a file containing the text mostly harmless (and a trailing newline) as earth.txt in your download directory. To set the file contents from javascript instead, call this function first:

function setSaveFile(contents, file_name, mime_type) {
  var a = document.getElementById('save');
  mime_type = mime_type || 'application/octet-stream'; // text/html, image/png, et c
  if (file_name) a.setAttribute('download', file_name);
  a.href="https://stackoverflow.com/questions/4309958/data:"+ mime_type +';base64,'+ btoa(contents || '');
}

Leave a Comment