Client-Side File Generation and File Downloads on Modern Browsers

Sometimes, you just need an extension method to generate and download files from the client-side of most modern browsers. The only real takeaway from the code below is that Internet Explorer browser agents like to behave differently and require a different function call to provide this type of functionality. Other than that its pretty clear-cut, with most other modern browsers supporting the download attribute.

$(document).ready(function() {
    saveFile("Example.txt", "data:attachment/text", "Hello, world.");
});

function saveFile (name, type, data) {
    if (data != null && navigator.msSaveBlob)
        return navigator.msSaveBlob(new Blob([data], { type: type }), name);
    var a = $("<a style='display: none;'/>");
    var url = window.URL.createObjectURL(new Blob([data], {type: type}));
    a.attr("href", url);
    a.attr("download", name);
    $("body").append(a);
    a[0].click();
    window.URL.revokeObjectURL(url);
    a.remove();
}