Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a file using javascript in Mozilla Firefox

I want to write a function in javascript which creates a file and write some content to it, iam working with firefox, can anybody help me in this case.

Thanks...

like image 770
minu Avatar asked Jun 18 '10 07:06

minu


1 Answers

You can write files in JavaScript in Firefox, but you have to use an XPCOM object (internal browser API). This is not allowed for JavaScript loaded from a web page, and it is intended to be used by JavaScript running inside a Firefox add-on (with high level of privileges).

There is a way for unprivileged (web page) JavaScript to request more privileges and if the user grants it (there will be a pop up dialog asking for permission), the web page code would be able to write to a file.

But before you read further, a warning:

This is not standard JavaScript and I would not recommend this approach unless you are developing a very specific application, that will be used in a very specific way (like for example, http://www.tiddlywiki.com/ a client-side JavaScript-HTML only wiki).

Requesting XPCOM privileges on a website is a bad practice! It's basicly equivalent to running an .exe you just downloaded from a site. You are asking a user to grant full access to their computer (read, write, execute) with the identity of the user running Firefox.

Request permission to use XPCOM (this will prompt the user for confirmation, no way to avoid it):

netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");

Then, write to a file using an XPCOM object (example code from Mozilla Developer Network):

   1. // file is nsIFile, data is a string  
   2. var foStream = Components.classes["@mozilla.org/network/file-output-stream;1"].  
   3.                          createInstance(Components.interfaces.nsIFileOutputStream);  
   4.   
   5. // use 0x02 | 0x10 to open file for appending.  
   6. foStream.init(file, 0x02 | 0x08 | 0x20, 0666, 0);   
   7. // write, create, truncate  
   8. // In a c file operation, we have no need to set file mode with or operation,  
   9. // directly using "r" or "w" usually.  
  10.   
  11. // if you are sure there will never ever be any non-ascii text in data you can   
  12. // also call foStream.writeData directly  
  13. var converter = Components.classes["@mozilla.org/intl/converter-output-stream;1"].  
  14.                           createInstance(Components.interfaces.nsIConverterOutputStream);  
  15. converter.init(foStream, "UTF-8", 0, 0);  
  16. converter.writeString(data);  
  17. converter.close(); // this closes foStream  

You can find more information about I/O in Firefox using XPCOM here: https://developer.mozilla.org/en-US/docs/Code_snippets/File_I_O

like image 121
flpmor Avatar answered Sep 22 '22 23:09

flpmor