如何从Firefox插件中加载文件

Zar*_*nen 10 javascript firefox firefox-addon

我正在开发一个Firefox插件,其中包含一个包含一些HTML数据的文件.如何将此文件作为字符串加载?

我可以

var contents = Components.utils.import("resource://stuff.html");
Run Code Online (Sandbox Code Playgroud)

但然后尝试以Javascript的形式执行XML文件.我只想要它的内容!

Bru*_*oLM 10

使用此功能,您可以读取带有chrome范围的文件.

function Read(file)
{
    var ioService=Components.classes["@mozilla.org/network/io-service;1"]
        .getService(Components.interfaces.nsIIOService);
    var scriptableStream=Components
        .classes["@mozilla.org/scriptableinputstream;1"]
        .getService(Components.interfaces.nsIScriptableInputStream);

    var channel=ioService.newChannel(file,null,null);
    var input=channel.open();
    scriptableStream.init(input);
    var str=scriptableStream.read(input.available());
    scriptableStream.close();
    input.close();
    return str;
}

var contents = Read("chrome://yourplugin/stuff.html");
Run Code Online (Sandbox Code Playgroud)

加载CSS内容和注入页面的示例.

编辑:

只是为了更新它,因为它有点方便!

let { Cc, Ci } = require('chrome');
function read(file){
    var ioService = Cc["@mozilla.org/network/io-service;1"]
        .getService(Ci.nsIIOService);
    var scriptableStream = Cc["@mozilla.org/scriptableinputstream;1"]
        .getService(Ci.nsIScriptableInputStream);

    var channel = ioService.newChannel2(file, null, null, null, null, null, null, null);
    var input = channel.open();
    scriptableStream.init(input);
    var str = scriptableStream.read(input.available());

    scriptableStream.close();
    input.close();
    return str;
}
Run Code Online (Sandbox Code Playgroud)


rac*_*ack 6

对于Firefox中的文件系统交互,请使用Mozilla XPCOM组件.I/O XPCOM组件有一些包装器,例如JSLibio.js

使用io.js它是这样的:

var file = DirIO.get("ProfD"); // Will get you profile directory
file.append("extensions"); // extensions subfolder of profile directory
file.append("{1234567E-12D1-4AFD-9480-FD321BEBD20D}"); // subfolder of your extension (that's your extension ID) of extensions directory
// append another subfolder here if your stuff.xml isn't right in extension dir
file.append("stuff.xml");
var fileContents = FileIO.read(file);
var domParser = new DOMParser();
var dom = domParser.parseFromString(fileContents, "text/xml");
// print the name of the root element or error message
dump(dom.documentElement.nodeName == "parsererror" ? "error while parsing" : dom.documentElement.nodeName);
Run Code Online (Sandbox Code Playgroud)