I have this Javascript code that downloads a CSV
.
In Chrome it works perfectly but in IE8/IE11 it doesn't.
var csv = "sep=,\nMatrícula:,\nDepartamento:,\nNombre:,Rrhh Desarrollador 01,\nTeléfono:,,\nFactoría:,\nEmail:,[email protected], [email protected],\nEmpresa:,";
var link = document.createElement("a");
link.setAttribute("href", "data:text/csv;charset=utf-8,%EF%BB%BF" + escape(csv));
link.setAttribute("download", "prueba.csv");
link.click();
It does not give any type of error in the console. It runs everything but does not download the file.
I have tried creating a blob element but it only works for IE10+
var csv = "sep=,\nMatrícula:,\nDepartamento:,\nNombre:,Rrhh Desarrollador 01,\nTeléfono:,,\nFactoría:,\nEmail:,[email protected], [email protected],\nEmpresa:,";
var a = document.createElement('a'),
file = new Blob([csv], {
type: 'text/csv;charset=utf-8,%EF%BB%BF'
});
if (window.navigator.msSaveBlob) window.navigator.msSaveBlob(file, "prueba.csv");
else {
a.href = URL.createObjectURL(file), a.download = "prueba.csv";
document.body.appendChild(a);
a.click();
}
As a possible solution, the execCommand -> SaveAs
(thanks to Guillermo's response) but it seems cumbersome to me since it opens a new window with the text csv
as the body of the web page and then opens a download dialog where it says that you will download a .html
despite the fact that it is.csv
var oWin = window.open("about:blank", "_blank");
oWin.document.writeln(csv);
oWin.document.close();
oWin.document.execCommand('SaveAs', true, "prueba.csv")
oWin.close();
But it doesn't work with Chrome or IE11... and I want to have the minimum number of codes for different browsers...
How do I make it compatible for IE8 without using execCommand
?
Try this:
Here is a small tutorial on how to download cross-platform csv and json
I suggest you try the Downloadify library .
Brief explanation
This library is a tiny JavaScript + Flash library that allows you to generate files at once, in the browser, without interaction with the server. Web applications that allow you to generate vCards, color palettes, custom code, etc. they would benefit from using this library. In addition to increasing speed (without a round trip to the server), this solution can reduce the load on existing web application servers and databases. This is not a library to 'force download' a file from a server. It does not interact with a server at all.
dependencies
The end user must have Flash 10 or higher installed for this plugin to work.
Downloadify only depends on SWFObject 2.0 which is included with the download. It is compatible with any JavaScript framework but has a helper for jQuery and MooTools...
They have a demo page , you can test how it works online.