views:

120

answers:

5

I'm working on a Firefox plugin which contains a file holding some HTML data. How do I load in this file as a string?

I can do

var contents = Components.utils.import("resource://stuff.html");

but that then tries to execute the XML file as Javascript. I just want its contents!

A: 

Components.utils.import is used for Javascript Code Modules.

If you want to use that command, you have to store the data as JSON.

JSON is somewhat similar to XML, in that it's designed for data, but JSON is easily integrated with Javascript code.

Kranu
+2  A: 

For filesystem interactions in Firefox, use Mozilla XPCOM components. There are some wrappers for I/O XPCOM components such as JSLib and io.js

Using io.js it'd be something like:

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);
racetrack
Which XPCOM components? I really cannot get to grips with the Firefox documentation, which seems to have no index of available components. Also, if I specify a relative path in FileIO.open, where will it be rooted?
Zarkonnen
@Zarkonnen Updated the sample code. You need Mozilla I/O XPCOM components (@mozilla.org/file/*)
racetrack
A: 

I think you are looking for nsILocalFile.

kizzx2
+5  A: 

I think these links would be quite helful... These tell how to implement Json as well as some stuff about the firefox interfaces

http://www.json.org/js.html

https://developer.mozilla.org/en/JSON

Hope it helps :)

sumit_programmer
+1  A: 

Using this function you can read files withing chrome scope.

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");

Example loading CSS content and injecting on a page.

BrunoLM
Thank you for this answer, which is very useful, and the right one - but I ended up finding my solution via racetrack's answer, so I've given them the bounty.
Zarkonnen