Markcce Eros Markcce Eros - 15 days ago 7
Javascript Question

Javascript csv download file not working on firefox

I have some code which downloads some data into a csv file which works great on chrome but doesn't do anything on firefox (no errors)

Here is the code:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>

<script>

var data = [
['idea', 'a very good one'],
['beer', 'not when driving'],
['guitar', 'yes please']
];


function download_csv() {
var csv = 'Name,Title\n';
data.forEach(function(row) {
csv += row.join(',');
csv += "\n";
});

console.log(csv);
var hiddenElement = document.createElement('a');
hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csv);
hiddenElement.target = '_blank';
hiddenElement.download = 'test.csv';
hiddenElement.click();
}

</script>

<button onclick="download_csv()">Download CSV</button>

</body>
</html>


Why is it not working in firefox?

Answer

You are creating an element and invoking the click event of the element without adding the same to the DOM. That's why it's not working in FireFox.

I created a hidden div <div id="container" style="display:none;"></div> and appended the hiddenElement you created to this div then trigger the click event which is now causing FireFox to download the csv.

That's it :-)

I tested in FireFox and Chrome and both are looking good.

Modified code:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title></title>
  <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>

    <script>

        var data = [
           ['idea', 'a very good one'],
           ['beer', 'not when driving'],
           ['guitar', 'yes please']
        ];


        function download_csv() {
            var csv = 'Name,Title\n';
            data.forEach(function(row) {
                    csv += row.join(',');
                    csv += "\n";
            });

            console.log(csv);
            var hiddenElement = document.createElement('a');
            hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csv);
            hiddenElement.target = '_blank';
            hiddenElement.download = 'test.csv';
            document.getElementById('container').appendChild(hiddenElement);
            hiddenElement.click();
        }

    </script>

    <button onclick="download_csv()">Download CSV</button>
    <div id="container" style="display:none;"></div>
</body>
</html>

Comments