2

I understand javascript is not designed for file manipulation due to security concerns. However, recently I figured out a way to read files using firefox. Is there a way to write to a file as well?

I found the following two potential solutions:

  1. How to enable local javascript to read/write files on my PC?
  2. https://developer.mozilla.org/en/Code_snippets/File_I%2F%2FO

However, since I am extremely inexperienced in this matter I did not figure out how to use either of them. Could anyone provide a very basic example please?

Thanks

Edit: I tried to use 1. to write to a file, but it work here is what I wrote:

  1. WritingJS.html: http://pastebin.com/ZSztcgNx
  2. selfcontainedmap2.js: http://pastie.org/3391242

My firefox is a clean install of Firefox 8, hence there shouldn't be any addon conflicts I suppose.

Community
  • 1
  • 1
JavaNoob
  • 47
  • 1
  • 2
  • 7
  • The accepted answer in your first link not only provides all the code, but an example of reading from a file (right below the first code). Writing is the same thing, except you pass an extra parameter that is the text you want written. – Ken White Feb 15 '12 at 22:42
  • Hi, thanks for replying. I tried to use it but could not get it to work. I have edited the original question to include what I wrote. Could you spot any mistakes I made? Thank you. – JavaNoob Feb 16 '12 at 00:35
  • This solution here shows you how to use HTML5 to save files but when wanting to save to local drive you need user input: http://stackoverflow.com/a/13779352/1828637 – Noitidart Feb 09 '15 at 08:46

2 Answers2

2

You won't be able to access the XPCOM components from non-privileged code.

What that means in English is that those APIs are only available to things like addons running on the browser, not on website code.

There is no way (and will never be a way for security reasons) for a website to read/write local files, apart from cookies, without some plugin like flash providing a way of doing it.

Howard
  • 3,855
  • 1
  • 15
  • 12
  • 2
    The question is tagged firefox-addon. – Matthew Flaschen Feb 15 '12 at 23:23
  • 1
    @MatthewFlaschen I didn't notice that. Should have been made clearer in the question IMHO, easy to miss that. Thanks for pointing it out. – Howard Feb 15 '12 at 23:55
  • Thanks for replying. I edited my original post to include a SCCE of what I tried to do. It, however, did not work. Could you spot any mistakes? Thanks. – JavaNoob Feb 16 '12 at 00:36
1
function WriteToFile()
{
var fso = new ActiveXObject("Scripting.FileSystemObject");
var s = fso.CreateTextFile("C:\\NewFile.txt", true);
var text=document.getElementById("TextArea1").innerTex;
s.WriteLine(text);
s.Close();
}

You can write text to a file and save it in the local drive. A very basic example is as follows,

The TextArea1 is the id of a form element which contains the target text. The function can be called in a button click event.

Hope that helps!

Anto
  • 71
  • 1
  • 8