Search code examples
javascriptcsvgoogle-chromedata-uri

How to download CSV using a href with a # (number sign) in Chrome?


Chrome 72+ is now truncating our data at the first sign of a # character.

https://bugs.chromium.org/p/chromium/issues/detail?id=123004#c107

We have been using a temp anchor tag along with the download attribute and href attribute with a csv string to download a csv of data on the page to the user's machines. This is now broken in a recent Chrome update because all data after the first # sign is stripped from the downloaded csv.

We can work around it by replacing the # with " num " or other data, but that leaves our csv/excel files with different data which we'd like to avoid.

Is there any work around we can do to prevent chrome from stripping out the data in the href when downloading the file?

let csvContent = "data:text/csv;charset=utf-8,";
let header = "Col1, Col2, Col3";
csvContent += header + "\r\n";
csvContent += "ac, 123, info here" + "\r\n";
csvContent += "dfe, 432, #2 I break" + "\r\n";
csvContent += "fds, 544, I'm lost due to previous number sign";

var encodedUri = encodeURI(csvContent);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "file.csv");
document.body.appendChild(link);
link.click();

I tried replacing the # with a unicode character of which was close enough, and looked fine in the CSV, but Excel did not like the unicode characters


Solution

  • I ran into this same problem, the only change that I did was keeping the "data:text/csv;charset=utf-8," unencoded and just endoding the CSV data portion and use encodeURIComponent instead of encodeURI like so:

    let prefix = "data:text/csv;charset=utf-8,";
    let header = "Col1, Col2, Col3";
    let csvContent = header + "\r\n";
    csvContent += "ac, 123, info here" + "\r\n";
    csvContent += "dfe, 432, #2 I break" + "\r\n";
    csvContent += "fds, 544, I'm lost due to previous number sign";
    
    var encodedUri = prefix + encodeURIComponent(csvContent);
    var link = document.createElement("a");
    link.setAttribute("href", encodedUri);
    link.setAttribute("download", "file.csv");
    document.body.appendChild(link);
    link.click();

    Copy and paste that into a Chrome console window and it works as expected.