Create a blob with the csv data .ie var blob = new Blob([data], type:"text/csv");
If the browser supports saving of blobs i.e if window.navigator.mSaveOrOpenBlob)===true
, then save the csv data using: window.navigator.msSaveBlob(blob, 'filename.csv')
If the browser doesn't support saving and opening of blobs, then save csv data as:
var downloadLink = document.createElement('<a></a>');
downloadLink.attr('href', window.URL.createObjectURL(blob));
downloadLink.attr('download', filename);
downloadLink.attr('target', '_blank');
document.body.append(downloadLink);
Full Code snippet:
var filename = 'data_'+(new Date()).getTime()+'.csv';
var charset = "utf-8";
var blob = new Blob([data], {
type: "text/csv;charset="+ charset + ";"
});
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveBlob(blob, filename);
} else {
var downloadLink = document.element('<a></a>');
downloadLink.attr('href', window.URL.createObjectURL(blob));
downloadLink.attr('download', filename);
downloadLink.attr('target', '_blank');
document.body.append(downloadLink);
downloadLink[0].click();
}