If we were on the node of the JS server, we could write the header, set the mime type and send it:
res.header("Content-Disposition", "attachment;filename="+name+".csv"); res.type("text/csv"); res.send(200, csvString);
and because of the headers, the browser will create a download for the named csv file.
When useful data is generated in the browser, one of the solutions for receiving it in a CSV file is to use ajax, upload it to the server (perhaps, if necessary, save it there) and force the server to send it with these headers to load csv in the browser.
However, I would like the 100% browser solution to not include ping pong with the server.
So it occurred to me that you could open a new window and try to set a title with the equivalent of the META tag.
But this does not work for me in recent Chrome.
I get a new window and it contains csvString, but it does not fulfill the load function.
I think I expected to get either the download on the bottom tab, or an empty new window with the download on the bottom tab.
I am wondering if the meta tags are correct or if other tags are needed.
Is there any way to do this work without clicking on the server?
JsFiddle for creating CSV in the browser (does not work - displays a window, but without loading)
var A = [['n','sqrt(n)']]; // initialize array of rows with header row as 1st item for(var j=1;j<10;++j){ A.push([j, Math.sqrt(j)]) } var csvRows = []; for(var i=0,l=A.length; i<l; ++i){ csvRows.push(A[i].join(',')); // unquoted CSV row } var csvString = csvRows.join("\n"); console.log(csvString); var csvWin = window.open("","",""); csvWin.document.write('<meta name="content-type" content="text/csv">'); csvWin.document.write('<meta name="content-disposition" content="attachment; filename=data.csv"> '); csvWin.document.write(csvString);