JavaScript: Create and save file [duplicate] JavaScript: Create and save file [duplicate] javascript javascript

JavaScript: Create and save file [duplicate]


A very minor improvement of the code by Awesomeness01 (no need for anchor tag) with addition as suggested by trueimage (support for IE):

// Function to download data to a filefunction download(data, filename, type) {    var file = new Blob([data], {type: type});    if (window.navigator.msSaveOrOpenBlob) // IE10+        window.navigator.msSaveOrOpenBlob(file, filename);    else { // Others        var a = document.createElement("a"),                url = URL.createObjectURL(file);        a.href = url;        a.download = filename;        document.body.appendChild(a);        a.click();        setTimeout(function() {            document.body.removeChild(a);            window.URL.revokeObjectURL(url);          }, 0);     }}

Tested to be working properly in Chrome, FireFox and IE10.

In Safari, the data gets opened in a new tab and one would have to manually save this file.


function download(text, name, type) {  var a = document.getElementById("a");  var file = new Blob([text], {type: type});  a.href = URL.createObjectURL(file);  a.download = name;}
<a href="" id="a">click here to download your file</a><button onclick="download('file text', 'myfilename.txt', 'text/plain')">Create file</button>