23

I'm writing a sidebar extension for Firefox and need a way to get the URL of the current page so I can check it against a database and display the results. How can I do this?

1
  • 1
    I think this question is about the old-school Firefox sidebars, and not the new sidebar SDK.
    – Flimm
    Jun 1, 2015 at 16:06

8 Answers 8

20

I stumbled over this post while looking for an answer to the same question.

Actually I think it's as easy as

alert(window.content.location.href)

See also https://developer.mozilla.org/en/DOM/window.content

1
  • 3
    This seems to work if you're overlaying the main browser window (browser.xul) but I don't know if it will work in other cases.
    – Tyler
    Jun 24, 2010 at 16:47
16
window.top.getBrowser().selectedBrowser.contentWindow.location.href;

might work, otherwise I think you need to use:

var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
                   .getInterface(Components.interfaces.nsIWebNavigation)
                   .QueryInterface(Components.interfaces.nsIDocShellTreeItem)
                   .rootTreeItem
                   .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
                   .getInterface(Components.interfaces.nsIDOMWindow);

mainWindow.getBrowser().selectedBrowser.contentWindow.location.href;
1
  • 1
    You may need to replace Components.interfaces to just Ci everywhere in the above answer. Refer stackoverflow.com/questions/12558983/… for more and also add const {Ci, components} = require("chrome") to the top of your script.
    – jobin
    Sep 18, 2013 at 16:10
5

This seems to work fine for me

function getCurrentURL(){

    var currentWindow = Components.classes["@mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator).getMostRecentWindow("navigator:browser");

    var currBrowser = currentWindow.getBrowser();
    var currURL = currBrowser.currentURI.spec;

    return currURL;
}
2
  • you should add function getCurrentURL(){ and } to the code layout. They're part of the code.
    – dierre
    Sep 21, 2010 at 18:15
  • this is a good choice as when a new tab is open is gets that URL instead in case of @Wimmel it doesn't. Thanks. Oct 31, 2010 at 11:14
2

https://developer.mozilla.org/En/Working_with_windows_in_chrome_code

If you need to access the main browser from the code running in a sidebar, you'll something like what Wimmel posted, except the last line could be simplified to

mainWindow.content.location.href

(alternatively you could use 's API returning an nsIURI).

Depending on your task, it might make sense to run the code in the browser window instead (e.g. in a page load handler), then it can access the current page via the content shortcut and the sidebar via document.getElementById("sidebar").contentDocument or .contentWindow.

1

If you need only domain and subdomain;

Usage;

PageDomain.getDomain(); // stackoverflow.com
PageDomain.getSubDomain(); //  abc.stackoverflow.com

Code;

PageDomain = {

getDomain : function() {
    var docum = Components.classes["@mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator).getMostRecentWindow("navigator:browser");
    var domain = PageDomain.extractDomain(new String(docum.location));
    return domain;
},
getSubDomain : function() {
    var docum = Components.classes["@mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator).getMostRecentWindow("navigator:browser");
    var subDomain = PageDomain.extractSubDomain(new String(docum.location));
    return subDomain;
},
 extractDomain: function(host) {
        var s;

        // Credits to Chris Zarate
        host=host.replace('http:\/\/','');
        host=host.replace('https:\/\/','');
        re=new RegExp("([^/]+)");
        host=host.match(re)[1];
        host=host.split('.');

        if(host[2]!=null) {
          s=host[host.length-2]+'.'+host[host.length-1];
          domains='ab.ca|ac.ac|ac.at|ac.be|ac.cn|ac.il|ac.in|ac.jp|ac.kr|ac.nz|ac.th|ac.uk|ac.za|adm.br|adv.br|agro.pl|ah.cn|aid.pl|alt.za|am.br|arq.br|art.br|arts.ro|asn.au|asso.fr|asso.mc|atm.pl|auto.pl|bbs.tr|bc.ca|bio.br|biz.pl|bj.cn|br.com|cn.com|cng.br|cnt.br|co.ac|co.at|co.il|co.in|co.jp|co.kr|co.nz|co.th|co.uk|co.za|com.au|com.br|com.cn|com.ec|com.fr|com.hk|com.mm|com.mx|com.pl|com.ro|com.ru|com.sg|com.tr|com.tw|cq.cn|cri.nz|de.com|ecn.br|edu.au|edu.cn|edu.hk|edu.mm|edu.mx|edu.pl|edu.tr|edu.za|eng.br|ernet.in|esp.br|etc.br|eti.br|eu.com|eu.lv|fin.ec|firm.ro|fm.br|fot.br|fst.br|g12.br|gb.com|gb.net|gd.cn|gen.nz|gmina.pl|go.jp|go.kr|go.th|gob.mx|gov.br|gov.cn|gov.ec|gov.il|gov.in|gov.mm|gov.mx|gov.sg|gov.tr|gov.za|govt.nz|gs.cn|gsm.pl|gv.ac|gv.at|gx.cn|gz.cn|hb.cn|he.cn|hi.cn|hk.cn|hl.cn|hn.cn|hu.com|idv.tw|ind.br|inf.br|info.pl|info.ro|iwi.nz|jl.cn|jor.br|jpn.com|js.cn|k12.il|k12.tr|lel.br|ln.cn|ltd.uk|mail.pl|maori.nz|mb.ca|me.uk|med.br|med.ec|media.pl|mi.th|miasta.pl|mil.br|mil.ec|mil.nz|mil.pl|mil.tr|mil.za|mo.cn|muni.il|nb.ca|ne.jp|ne.kr|net.au|net.br|net.cn|net.ec|net.hk|net.il|net.in|net.mm|net.mx|net.nz|net.pl|net.ru|net.sg|net.th|net.tr|net.tw|net.za|nf.ca|ngo.za|nm.cn|nm.kr|no.com|nom.br|nom.pl|nom.ro|nom.za|ns.ca|nt.ca|nt.ro|ntr.br|nx.cn|odo.br|on.ca|or.ac|or.at|or.jp|or.kr|or.th|org.au|org.br|org.cn|org.ec|org.hk|org.il|org.mm|org.mx|org.nz|org.pl|org.ro|org.ru|org.sg|org.tr|org.tw|org.uk|org.za|pc.pl|pe.ca|plc.uk|ppg.br|presse.fr|priv.pl|pro.br|psc.br|psi.br|qc.ca|qc.com|qh.cn|re.kr|realestate.pl|rec.br|rec.ro|rel.pl|res.in|ru.com|sa.com|sc.cn|school.nz|school.za|se.com|se.net|sh.cn|shop.pl|sk.ca|sklep.pl|slg.br|sn.cn|sos.pl|store.ro|targi.pl|tj.cn|tm.fr|tm.mc|tm.pl|tm.ro|tm.za|tmp.br|tourism.pl|travel.pl|tur.br|turystyka.pl|tv.br|tw.cn|uk.co|uk.com|uk.net|us.com|uy.com|vet.br|web.za|web.com|www.ro|xj.cn|xz.cn|yk.ca|yn.cn|za.com';
          domains=domains.split('|');
          for(var i=0;i<domains.length;i++) {
            if(s==domains[i]) {
              s=host[host.length-3]+'.'+s;
              break;
            }
          }
        } else {
          s=host.join('.');
        }
        // Thanks Chris
        return s;
      },

      extractSubDomain:function(host){
          host=host.replace('http:\/\/','');
          host=host.replace('https:\/\/','');
          re=new RegExp("([^/]+)");
          host=host.match(re)[1];
          return host;
      }
}
0

From a Firefox extension popup ;

You'll need

"permissions": [
  "activeTab"
]

in your manifest or possibly tabs instead of activeTab

async function getCurrentTabUrl(){
    let tabs = await browser.tabs.query({active: true, currentWindow: true}) ;
    return tabs[0].url ;
}

let hostUrl = await getCurrentTab();
alert(hostUrl);
0

This works from a firefox "popup" extension.

browser.tabs.query({active: true, windowId: browser.windows.WINDOW_ID_CURRENT})
    .then(tabs => browser.tabs.get(tabs[0].id))
    .then(tab => {
    console.log(tab);    
    });
-1

Hallo,

I have tried to implement this in JavaScript, because I need that in my project too, but all three possible solutions didn't work. I have also implemented a small site to test it, but this also didn't work.

Here is the source code of the small site:

<html>
<head>
<title>Test</title>
<script type="text/javascript">
function Fall1 () {

    alert(window.top.getBrowser().selectedBrowser.contentWindow.location.href);
}

function Fall2() {
var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
                   .getInterface(Components.interfaces.nsIWebNavigation)
                   .QueryInterface(Components.interfaces.nsIDocShellTreeItem)
                   .rootTreeItem
                   .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
                   .getInterface(Components.interfaces.nsIDOMWindow);

alert(mainWindow.getBrowser().selectedBrowser.contentWindow.location.href);
}

function Fall3() {
alert(document.getElementById("sidebar").contentWindow.location.href);
}

</script>
</head>
<body>
<form name="Probe" action="">

<input type="button" value="Fall1"
onclick="Fall1()">

<input type="button" value="Fall2"
onclick="Fall2()">

<input type="button" value="Fall3"
onclick="Fall13()">
</form>
</body>
</html>
1
  • 1
    Javascript in a webpage doesn't behave the same way as Javascript in a Firefox addon. When you're writing a webpage, document refers to that webpage. When you're writing an addon, document refers to the XUL document that the script is embedded in.
    – Tyler
    Jun 24, 2010 at 16:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.