0

I'm trying to create and download a file on client side with the following code:

function downloadFile(filename, text) {
    var pom = document.createElement('a');
    pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
    pom.setAttribute('download', filename);
    pom.click();
}

Although this only works on chrome. Nothing happens on safari and IE. How can I make it work?

Sina Sohi
  • 2,719
  • 9
  • 33
  • 50

2 Answers2

0

Not sure if youve figured this out or not but for this to work in safari you need to create an event and dispatch on the created element like this:

    var downloadLink = document.createElement('a');
    downloadLink.setAttribute('href', 'data:application/octet;charset=utf-8,' + encodeURIComponent(data));
    downloadLink.setAttribute('download', fileName);
    downloadLink.style.display = "none";
    downloadLink.onclick = function (event) {
        document.body.removeChild(event.target);
    };

    var clk = document.createEvent("MouseEvent");
    clk.initEvent("click", true, true);
    downloadLink.dispatchEvent(clk);

    document.body.appendChild(downloadLink);
    downloadLink.dispatchEvent(clk);`
Alex
  • 1,161
  • 1
  • 7
  • 7
-1

I used this to save my file in CSV/excel format and works in chrome/IE/Safari
refer and make changes needed

        var fileName = name + "["+ name1 +"]";
        var uri = 'data:text/csv;charset=utf-8,' + escape(finalResult);
        var link = document.createElement("a");    
        link.href = uri;
        link.style = "visibility:hidden";
        link.download = fileName + ".csv";
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        location.reload();
User1038
  • 435
  • 2
  • 6
  • 17
  • 1
    Hi, this doesn't work on safari or IE still. I've copy pasted your code and made changes to filename and finalResult, but nothing happens on IE or safari. :( – Sina Sohi Apr 22 '14 at 08:59