This function sets up both a hard-coded file object and one that's got a relative path -- in this case, to the Desktop. (More on the choices for special, relative file locations here.)

Right now, it's hooked up to write out to a file called Output.txt on whatever your local OS believes is the desktop (or whatever it tells Firefox it believes is the desktop...). It's a simple task to swap out for the hard-coded file path if you'd rather.

This is working for me in Firefox 4.0. Paste it into the top of whatever js file you've got in chrome and call away with

writeToFile("This is what you'll be writing to a file.").

Got it? Here's the code.

// various sources for portions of this came from...
function writeToFile(strTextToWrite) {

// if you don't want to hard-code,
// blast from here...
var strOutFilePath = "~/out.txt"; // this is Mac OS X-ese here.
// strOutFilePath = "C:\\out.txt"; // this is more Windows-y
var outFile = Components.classes[";1"].
alert("file path: " + strOutFilePath);
if ( outFile.exists() == false ) {
alert("File does not exist, " +
"but that shouldn't matter now, I think");
// to here

// create a relative path
// should be the desktop, even cross platform
var fileOnDesk = Components.classes[";1"].
get("Desk", Components.interfaces.nsIFile);
// append to that crossplatform file (a folder) a specific doc name
if (!fileOnDesk.exists()) {
fileOnDesk.createUnique(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 0666);
// 666 = 400+200+40+20+4+2 = r/w owner, groups, others


var foStream = Components.classes[";1"]

strTextToWrite += "\n";
// to use the hard-coded outFile, swap fileOnDesk out for outFile
foStream.init(fileOnDesk, 0x02 | 0x08 | 0x10, 00666, 0);
foStream.write(strTextToWrite, strTextToWrite.length);

Labels: , , ,