Here is the code I used for Firefox, which is not portable, but works:
As OP commented, enablePrivilege()
has been deprecated, this should be considered usable. But as my Firefox using previous profile still work with my code, so I dig a little into the prefs.js
(as about:config
is hiding these settings,) And here is the settings you need you get it work.
user_pref("capability.principal.codebase.p0.granted", "UniversalXPConnect");
user_pref("capability.principal.codebase.p0.id", "file://"); // path to the html file.
user_pref("capability.principal.codebase.p0.subjectName", "");
And here goes the code:
var File = function(file) {
netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
var ios = Components.classes["@mozilla.org/network/io-service;1"]
.getService(Components.interfaces.nsIIOService);
if (!File.baseURI) {
File.baseURI = ios.newURI(location.href.substring(0, location.href.lastIndexOf("https://stackoverflow.com/")+1), null, null);
File.baseFolder = File.baseURI.QueryInterface(Components.interfaces.nsIFileURL).file.path;
}
var URL = ios.newURI(file, null, File.baseURI);
this.fptr = URL.QueryInterface(Components.interfaces.nsIFileURL).file;
}
File.prototype = {
write: function(data) {
netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
var foStream = Components.classes["@mozilla.org/network/file-output-stream;1"]
.createInstance(Components.interfaces.nsIFileOutputStream);
foStream.init(this.fptr, 0x02 | 0x08 | 0x20, 0666, 0);
var converter = Components.classes["@mozilla.org/intl/converter-output-stream;1"]
.createInstance(Components.interfaces.nsIConverterOutputStream);
converter.init(foStream, null, 0, 0);
converter.writeString(data);
converter.close();
},
read: function() {
netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
var fstream = Components.classes["@mozilla.org/network/file-input-stream;1"]
.createInstance(Components.interfaces.nsIFileInputStream);
var cstream = Components.classes["@mozilla.org/intl/converter-input-stream;1"]
.createInstance(Components.interfaces.nsIConverterInputStream);
fstream.init(this.fptr, -1, 0, 0);
cstream.init(fstream, null, 0, 0);
var data = "";
// let (str = {}) { // use this only when using javascript 1.8
var str = {};
cstream.readString(0xffffffff, str);
data = str.value;
// }
cstream.close();
return data;
}
};