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