3

I need to download a csv file using javascript in IE 8 and IE9.I tried using window.open().

Here is my code:

var URI = 'data:text/csv;charset=utf-8,';
var fileName = "text.csv";

var testlink = window.open("about:blank", "_blank");

testlink.document.write(fileData); //fileData has contents for the file

testlink.document.close();

testlink.document.execCommand('SaveAs', false, fileName);

testlink.close();     

This opens a new window and prompts to save the file.After saving the file,it returns back to the page.Instead of opening a blank page,I need to download the file by staying in the page

Joe Enos
  • 39,478
  • 11
  • 80
  • 136
  • I was going to suggest an anchor with a `download` attribute, but that literally works on everything but IE. :\ Maybe [this other question](https://stackoverflow.com/questions/11631749/using-data-uris-to-prompt-the-user-to-save-files) will be of some use? – Mr. Llama Dec 04 '14 at 22:31
  • I tried that and it doesn't work on IE – Narayanan Ramsubramanyam Dec 04 '14 at 22:33
  • I haven't done it, so I don't know if it would work, but maybe try an iframe instead of a popup. – Joe Enos Dec 04 '14 at 22:38
  • From what I'm reading, `execCommand` is pretty hackish anyway. If there's any possibility of doing this from the server (whatever language/framework you may be using), I'd go with that, so you can properly set HTTP headers, be browser-agnostic, etc. – Joe Enos Dec 04 '14 at 22:47
  • I am trying that with Iframe.Can I download the iframe directly without using execCommand? Because Save As opens a new popup to save the file.I want it to be downloaded directly to the desktop – Narayanan Ramsubramanyam Dec 04 '14 at 22:47
  • 1
    @NarayananRamsubramanyam You want it to download, via scripting, without first prompting the user to accept the download? – Sampson Dec 05 '14 at 02:08
  • 1
    as @JonathanSampson hinted at, this is impossible to do. Think about if somebody made a virus, and then they downloaded it directly to the user's desktop! That'd be a huuuuuge security risk. The only way to download a file would be to have a prompt to the user and let them choose if they want to download it – markasoftware Dec 05 '14 at 02:10
  • In later version of IE (and modern browsers) you could use the File Api (IE10+) - otherwise you can't write a file to the users machine without their consent (same for all browsers when not using the File API). Its build right into the browser security model (all vendors) – Code Uniquely Dec 05 '14 at 05:17

0 Answers0