Entry

Allow users to save text as file in JavaScript

Solution

const text = document.querySelector("#text");
function onDownoadClick(e) {
    const aElem = e.target;
    if (!aElem.download) {
        const lang = text.dataset.language;
        let mimeType;
        switch(lang) {
            case "javascript":
            case "js":
                mimeType = "text/javascript"
                break;
            case "html":
                mimeType = "text/html";
                break;
            case "css":
                mimeType = "text/css";
                break;
            case "json":
                mimeType = "application/json";
                break;
            default:
                mimeType = "text/plain";
                break;
        }

        const contents = new Blob([], {type: mimeType});
        aElem.href = URL.createObjectURL(contents);
        aElem.download = "filename." + lang;
    }
}

The code above will generate a file on click and allow the user to download it in one go. Furthermore, the generated data is saved for future presses of the button.