Convert resource:// url to a full local file path?

Talk about add-ons and extension development.
Post Reply
User avatar
Vano
Posts: 403
Joined: December 26th, 2007, 8:21 pm

Convert resource:// url to a full local file path?

Post by Vano »

Hello.

Is there a way get full local path of a resource:// url?

For example resource://myaddon/modules/blah.jsm would become C:\Users\test\AppData\Roaming\Mozilla\Firefox\Profiles\asfasdf\extensions\myaddon@test\chrome\modules\blah.jsm


Thank you.

P.S.
To convert chrome:// addresses I use this:

Code: Select all

let url = "chrome://myaddon/content/blah.js",
    ios = Components.classes['@mozilla.org/network/io-service;1'].getService(Components.interfaces["nsIIOService"]),
    cr = Components.classes['@mozilla.org/chrome/chrome-registry;1'].getService(Components.interfaces["nsIChromeRegistry"])

url = cr.convertChromeURL(ios.newURI(url, "UTF-8", null)).spec;
morat
Posts: 6404
Joined: February 3rd, 2009, 6:29 pm

Re: Convert resource:// url to a full local file path?

Post by morat »

Try the nsIResProtocolHandler interface.

http://mxr.mozilla.org/mozilla-release/ ... oLocalPath
User avatar
Vano
Posts: 403
Joined: December 26th, 2007, 8:21 pm

Re: Convert resource:// url to a full local file path?

Post by Vano »

Thank you very much!

Here is working solution for file:// chrome:// and resource:// scheme urls:

Code: Select all

/**
 * http://mxr.mozilla.org/mozilla-release/source/devtools/server/actors/script.js#2086
 *
 * Resolve a URI back to physical file.
 *
 * Of course, this works only for URIs pointing to local resources.
 *
 * @param  aURI
 *         URI to resolve
 * @return
 *         resolved nsIURI
 */
function resolveURIToLocalPath(aURI) {
  let resolved;
  switch (aURI.scheme) {
    case "jar":
    case "file":
      return aURI;

    case "chrome":
      resolved = Cc["@mozilla.org/chrome/chrome-registry;1"].
                 getService(Ci.nsIChromeRegistry).convertChromeURL(aURI);
      return resolveURIToLocalPath(resolved);

    case "resource":
      resolved = Cc["@mozilla.org/network/protocol;1?name=resource"].
                 getService(Ci.nsIResProtocolHandler).resolveURI(aURI);
      aURI = Services.io.newURI(resolved, null, null);
      return resolveURIToLocalPath(aURI);

    default:
      return null;
  }
}

function getLocalPath(url)
{
    let uri = null;
    try
    {
        uri = resolveURIToLocalPath(ios.newURI(url, "UTF-8", null));
    }
    catch(e){}
    return uri ? uri.spec : uri;
}

console.log(getLocalPath("resource://gre/modules/Services.jsm"));
Noitidart
Posts: 1168
Joined: September 16th, 2007, 8:01 am

Re: Convert resource:// url to a full local file path?

Post by Noitidart »

Very cool thanks for sharing the solution!
Post Reply