Using HTML5/JavaScript to generate and save a file Using HTML5/JavaScript to generate and save a file javascript javascript

Using HTML5/JavaScript to generate and save a file


Simple solution for HTML5 ready browsers...

function download(filename, text) {    var pom = document.createElement('a');    pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));    pom.setAttribute('download', filename);    if (document.createEvent) {        var event = document.createEvent('MouseEvents');        event.initEvent('click', true, true);        pom.dispatchEvent(event);    }    else {        pom.click();    }}

Usage

download('test.txt', 'Hello world!');


OK, creating a data:URI definitely does the trick for me, thanks to Matthew and Dennkster pointing that option out! Here is basically how I do it:

1) get all the content into a string called "content" (e.g. by creating it there initially or by reading innerHTML of the tag of an already built page).

2) Build the data URI:

uriContent = "data:application/octet-stream," + encodeURIComponent(content);

There will be length limitations depending on browser type etc., but e.g. Firefox 3.6.12 works until at least 256k. Encoding in Base64 instead using encodeURIComponent might make things more efficient, but for me that was ok.

3) open a new window and "redirect" it to this URI prompts for a download location of my JavaScript generated page:

newWindow = window.open(uriContent, 'neuesDokument');

That's it.


HTML5 defined a window.saveAs(blob, filename) method. It isn't supported by any browser right now. But there is a compatibility library called FileSaver.js that adds this function to most modern browsers (including Internet Explorer 10+). Internet Explorer 10 supports a navigator.msSaveBlob(blob, filename) method (MSDN), which is used in FileSaver.js for Internet Explorer support.

I wrote a blog posting with more details about this problem.