How do I dynamically create a document for download in Javascript?

Posted by Nelson on Stack Overflow See other posts from Stack Overflow or by Nelson
Published on 2010-03-22T01:23:22Z Indexed on 2010/03/22 1:31 UTC
Read the original article Hit count: 477

Filed under:
|
|

I'm writing some Javascript code that generates an XML document in the client (via Google Earth plugin). I'd like the user to be able to click a button on the page and be prompted to save that XML to a new file. If I were generating the XML server-side this would be easy, just make the button open the link. But the XML is generated client-side.

I've come up with a couple of hacks that half-work, inspired in part by this StackOverflow question. But neither completely work. Here's a demo HTML with embedded code:

<html><head><script>
function getData() { return '<?xml version="1.0" encoding="UTF-8"?><doc>Hello</doc>'; }
function dlDataURI() {
  window.open("data:text/xml;charset=utf-8," + getData());
}
function dlWindow() {
  var w = window.open();
  w.document.open();
  w.document.write(getData());
  w.document.close();
}
</script><body>
<div onclick="dlDataURI()">Click for Data URL</div>
<div onclick="dlWindow()">Click for Window</div>
</body></html>

The dlDataURI() version works great in Firefox, poorly in Chrome (can't save), and not at all in IE. The Window() version works OK in Firefox and IE, and not well in Chrome (can't save, XML embedded inside HTML). Neither version ever prompts a user download, it always opens a new window trying to display the XML.

Is there a good way to do what I want in client side Javascript? I'd like this to work in today's browsers, ideally Firefox, MSIE 8, and Chrome.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about download