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.
Update with sample Downloadify code
window.onload = function() {
Downloadify.create("dlify", {
data: getData(),
filename: "data.xml",
swf: 'media/downloadify.swf',
downloadImage: 'images/download.png',
width: 100, height: 30});};