javascriptfiledownloadclient-side

Javascript: a SIMPLE way to save a text file?


I would like to offer to the user the opportunity to save his/her results, as displayed on the web page.

Using the browser's "save as" is no good, it saves the html code, or part of it, instead of saving what is displayed on the page. Even when the option is set to "save as text". There are local links etc.

Using localStorage would be worse. Imagine telling the user that his results are somewhere in a hidden directory and that he/she would need to decode sqlite files...

The examples I found online :

A) are too complicated

B) don't function

C) only show a bit of code and let you guess the rest

Some web sites offer "printer friendly" versions of their page. I could, on the click of a button, open in a new window, or tab, the list of results, in a no frill view. Then the user could "select all" and "copy/paste" to his/her favorite text editor. And save it.

I would like to do better. I would like to have a "Save results" button that would open the usual dialog box "where would you like to save this?" and offer, for instance, the choice between .txt and .rtf formats.

Some stuff I've read seem to hint that this would be illegal. If you could save as .exe, I would understand the security risk. But saving as .txt?


Solution


  • You can do it this way:
    <a href="#" id="download">Download</a>
    
    <script>
    var fileName = "myfile.txt";
    var fileContent = "Page content...";
    var myFile = new Blob([fileContent], {type: 'text/plain'});
    
    window.URL = window.URL || window.webkitURL;
    var dlBtn = document.getElementById("download");
    
    dlBtn.setAttribute("href", window.URL.createObjectURL(myFile));
    dlBtn.setAttribute("download", fileName);
    </script>
    

    This will ask the user to save a file called "myfile.txt" where they'd like to. The contents of the file is up to you.