Saving CSV file using blob in Safari

14,538

I did a quick research - I looks like Safari does not support what you are trying to achieve.

The reason why your solution works in Chrome (and Firefox) is that they support the download attribute - Safari doesn't yet.

Share:
14,538
Calvin Jeng
Author by

Calvin Jeng

Updated on June 04, 2022

Comments

  • Calvin Jeng
    Calvin Jeng almost 2 years

    I have codes below to generate the download link so that users could download the .csv file on my site.

    var link = document.createElement("a");
    link.id = "csvDwnLink";
    window.URL = window.URL || window.webkitURL;
    
    var csv = "\ufeff" + CSV,
        blob = new window.Blob([csv], {type: 'text/csv, charset=UTF-8'}),
        csvUrl = window.URL.createObjectURL(blob),
        filename = 'export.csv';
    
    $("#csvDwnLink").attr({'download': filename, 'href': csvUrl});
    $('#csvDwnLink')[0].click();
    document.body.removeChild(link);
    

    I hope the user could click the download link with csvUrl to download the cvs file.
    It works on chrome. However, when I click the same link using Safari, it will directly show me the content of the csv file in the tab.

    How do I solve this problem so that the safari will show the saving file window which user could select the path where they want to save the file instead of showing the content of the cvs file directly when I click the download link?
    Hope someone could me some recommendations or alternative methods.
    Thanks in advance!

    == Updated ==
    Find out solutions here
    solution 1, solution 2

    The code will be:

    var link = document.createElement("a");
    link.id = "csvDwnLink";
    
    document.body.appendChild(link);
    window.URL = window.URL || window.webkitURL;
    var csv = "\ufeff" + CSV,
        csvData = 'data:attachment/csv;charset=utf-8,' + encodeURIComponent(csv),
        filename = 'filename.csv';
    $("#csvDwnLink").attr({'download': filename, 'href': csvData});
    $('#csvDwnLink')[0].click();
    document.body.removeChild(link);
    

    Safari will download the file for the user, however, the file name will be unknown, probably it's because Safari don't support 'download' attribute yet as raphael mentioned.