Application requests KML data through AJAX from server. This data is stored in javascript variables, and displayed in Google Earth plugin.
In javascript, how do I
Yeah, I'm afraid you have to pass it back to the server. Make a generic "echo" script that spits out whatever parameters are fed to it.
At least you can force a download with the right MIME type:
"content-disposition","attachment; filename=data.xml"
Short answer: you can't and still be platform independent. Most browsers just don't allow javascript to manipulate the filesystem.
That said, you might be able to get away with some very platform-specific hacks. For example, IE offers the execCommand function, which you could use to call SaveAs. If you did that within an IFrame that had the data you wanted to save, you might get it working -- but only on IE. Other options (again, I'm going Microsoft specific here) include this Silverlight hack, or ActiveX controls.
I think for full platform compatibility, you're just going to have to suck it up and provide a server-side download option.
[Edit] Whoops! I didn't do enough due diligence when I went link-hunting. It turns out the Silverlight hack I linked to has a server-side component. Looks like you're pretty SOL.
[Edit2] I found a nice summary of browser compatibility for execCommand here. Although it lists question marks for the "saveas" command, maybe that might be a good route for you after all. Worth a try, perhaps?
[Edit3] Well, I decided to do a proof of concept of the approach I suggested, and I got something fairly simple working in IE. Unfortunately, I proved in the process that this approach will not work for Firefox and doesn't appear to work in Chrome/Safari, either. So it's very platform dependent. But it works! Here's a complete working page:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Javascript File Saver</title>
<script type="text/javascript">
function PageLoad() {
var fdoc = window.frames["Frame"].document;
fdoc.body.appendChild(fdoc.createTextNode("foo,bar,baz"));
}
function Save() {
var fdoc = window.frames["Frame"].document;
fdoc.execCommand("SaveAs", true);
}
</script>
</head>
<body onload="PageLoad();">
<h2>Javascript File Saver</h2>
<iframe id="Frame" style="width: 400px;">Noframe</iframe><br />
<button onclick="Save();">Save</button>
</body>
</html>