您可以在 Firefox 中使用 JavaScript 编写文件,但您必须使用 XPCOM 对象(内部浏览器 API)。这对于从网页加载的 JavaScript 是不允许的,它旨在供运行在 Firefox 插件中的 JavaScript 使用(具有高级别的权限)。
有一种方法可以让非特权(网页)JavaScript 请求更多权限,如果用户授予它(将弹出一个对话框询问权限),网页代码将能够写入文件。
但在您进一步阅读之前,请注意:
这不是标准的 JavaScript,除非您正在开发一个非常特定的应用程序,否则我不会推荐这种方法,它将以非常特定的方式使用(例如,http://www.tiddlywiki.com/ 仅客户端 JavaScript-HTML 的 wiki )。
在网站上请求 XPCOM 权限是一种不好的做法!它基本上等同于运行您刚刚从站点下载的 .exe。您要求用户以运行 Firefox 的用户的身份授予对其计算机的完全访问权限(读取、写入、执行)。
请求使用XPCOM的权限(这会提示用户确认,没有办法避免):
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
然后,使用 XPCOM 对象写入文件(来自 Mozilla 开发者网络的示例代码):
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
您可以在此处找到有关使用 XPCOM 在 Firefox 中 I/O 的更多信息:https://developer.mozilla.org/en-US/docs/Code_snippets/File_I_O