Search code examples
javascriptfirefox-addonxpcom

Get absolute url from relative url in firefox extension?


In my FF extension, I want to get the absolute URL of all the links in a page. I know this can be done by JS. But I want to know whether this can be done by any FF service.

Thanks for help.


Solution

  • First of all, getting an absolute URL of a link is trivial:

    console.log(doc.links[0].href);
    

    The href property of a link (not the href attribute) is always resolved automatically so that you get an absolute URL with no effort whatsoever.

    I suspect that what you really want is to resolve a relative URL that you got from somewhere. You use nsIIOService for this:

    var ioService = Components.classes["@mozilla.org/network/io-service;1"]
                              .getService(Components.interfaces.nsIIOService);
    var baseURI = ioService.newURI("http://example.com/index.html", null, null);
    var absURI = ioService.newURI("/test.gif", null, baseURI);
    console.log(absURI.spec);
    

    This example gives you http://example.com/test.gif as result, the relative URL /test.gif has been resolved relative to the page address http://example.com/index.html.