15

I have converted my existing data to text/csv and able to download the file in Chrome but when tried with Safari on iPad or Mac it opens a tab with name "unknown"/ "Untitled" . This is the code I am using -

var hiddenElement = document.createElement('a');                        
hiddenElement.href = 'data:text/csv,'+ encodeURI(response);
hiddenElement.target = '_blank';
hiddenElement.download = 'purchase.csv';
hiddenElement.click();

Is there anyway I can able to show the downloaded file as "purchase.csv" for safari.

Satyaki
  • 751
  • 2
  • 10
  • 25

2 Answers2

1

Try this one

var a = document.createElement('a');
a.setAttribute("href",URL);
a.setAttribute("target", "_blank");
var dispatch = document.createEvent("HTMLEvents");
dispatch.initEvent("click", true, true);
a.dispatchEvent(dispatch);
return false;
Arun Shinde
  • 1,185
  • 6
  • 12
1

IF the data is LOCAL -- Easy!

We just use window.URL.createObjectURL(). Let's set some globals...

//var response = Already defined by OP!  Not sure what it is, but it's data to save.
var mimetype = "text/csv";
var filename = "purchase.csv";

Now we just set the header by means of the type argument to window.URL.createObjectURL()...

a.href = window.URL.createObjectURL(new Blob([response], {
    encoding: "UTF-8",
    type: mimetype + ";charset=UTF-8",
}));

IF the data is on the WEB -- Still easy, just more effort!

We can do this by means of XMLHTTPRequest() to download the file data, window.URL.createObjectURL() to cast the data to a blob type with MIME type headers, and then proceed normally in setting a.download = filename; and a.click();.

An abstract function for download file data directly to the JavaScript environment...

function load(url, callback) {
  var xhr = new XMLHTTPRequest();
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) callback(xhr.responseText);
  };
  xhr.open("GET", url, true);
}

Then download the data, build the link, and click it:

load("site.com/t.txt", function (contents) {
    var a = window.document.createElement('a');
    a.href = window.URL.createObjectURL(new Blob([response], {
        encoding: "UTF-8",
        type: mimetype + ";charset=UTF-8",
    }));
    a.download = filename;

    document.body.appendChild(a);
    a.click();
    a.remove();
});
HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133