Perhaps this solution is a little more elegant, tested in Chrome, FF and ie7 to ie10, tested with text, JSON, PDF and XLS data (using the appropriate content type)
Either supply the saveFile()
function with a data blob, or create a data blob on the fly with type
set to nothing and your data between the []
's
In this example, we'll just stringify the settings
object, and set the datatype correctly.
settings = { any_kind_of_object: true };
json_str = JSON.stringify(settings);
saveFile('yourfilename.json', "data:application/json", new Blob([json_str],{type:""}));
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();
setTimeout(function(){ // fixes firefox html removal bug
window.URL.revokeObjectURL(url);
a.remove();
}, 500);
}