How to create a file and generate a download with Javascript in the Browser (without a server)

by cat_991

HTML

<textarea id="title-val" rows="2">This is the title of my file</textarea><br/><textarea id="text-val" rows="4">This is the content of my file</textarea><br/>
<input type="button" id="dwn-btn" value="Download"/>

JavaScript

function download(filename, text, extension) {
    var element = document.createElement('a');
    element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
    element.setAttribute('download', filename + "." + extension);

    element.style.display = 'none';
    document.body.appendChild(element);

    element.click();

    document.body.removeChild(element);
}

// Start file download.
document.getElementById("dwn-btn").addEventListener("click", function(){
    // Generate download of hello.txt file with some content
    var text = document.getElementById("text-val").value;
    var filename = document.getElementById("title-val").value;
    
    download(filename, text, "html");
}, false);