tags:

views:

114

answers:

3

I'd like to use Javascript to make IE6 download a file. It'll be created on the fly using Javascript. This file doesn't exist on a webserver. Here's a small example:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <script type="text/javascript">
function clicked() {
  var xml = "<data>Just for testing</data>";
  document.open("text/xml", "replace");
  document.write(xml);
}
    </script>
  </head>
  <body>
    <input type="button" value="Download" onclick="clicked();" />
  </body>
</html>

Instead of loading the xml in the browser window, I want it to cause IE6 to prompt the user where to download the data to so that it can be saved without them having to use File -> Save as. Any ideas?

A: 

No, this is not possible. A web-browser strictly doesn't allow this, as the ability to save files to disk through JavaScript only, would be very dangerous, even if the confirmation popup shows up.

EDIT: Thanks to other answers, I found out (not surprisingly) that this behavior is possible with some versione of IE.

Luca Matteis
I figured it would be something like that. What makes it more dangerous than clicking a link and downloading something malicious from a server?
Mark A. Nicolosi
XSS + user doesn't need to click perhaps
John Kugelman
Agreed, it is a terrible behavior for a browser to allow. However, IE does allow it through object.execCommand -- I'm not terribly surprised that it's the only browser that does ;)
Matt Bridges
With data coming from a server, the browser will tell you about the location of the data.
Luca Matteis
This is for an Intranet app at work. I wouldn't subject normal people on the web to such suckiness ;)
Mark A. Nicolosi
What do you mean "there is" ?
Luca Matteis
Luca: Huh? Are you replying to my comment on OrbMan's answer? If so, by there is no server, I meant there is no web server.
Mark A. Nicolosi
+2  A: 

For IE6 you should be able to use document.execCommand() after your document.write():

document.execCommand('SaveAs',true,'file.xml');

This is not part of any standard and will only work in IE flavor browsers.

Matt Bridges
This seems to work. Any chance I could prevent the browser from showing the content as well? The back button and refreshing don't reload the original page.
Mark A. Nicolosi
You could create an invisible or 0-by-0 iframe, and write the xml into that document instead of the main document.
Matt Bridges
Thank you Matt.
Mark A. Nicolosi
A: 

If your data must be generated client side, then you can post it back to the server so that it can be returned as a downloadable file.

RedFilter
There is no server, this will be running off a share on an Intranet. I'd love to write a Rails app to do this, but it unfortunately isn't an option. I've got to make do with what I have.
Mark A. Nicolosi