admin管理员组

文章数量:1425156

I followed the example code from the addon dev site have successfully put a button onto FF :) now i want to make that button do something interesting so I thought I would run an alert with the address that is currently in the bar... but this does not work:

CustomButton = {

1: function () {
  alert("Just testing 1"+document.location.href);
  },

}

except for the +document.location.href it's the exact demo code I got from the dev site...

I followed the example code from the addon dev site have successfully put a button onto FF :) now i want to make that button do something interesting so I thought I would run an alert with the address that is currently in the bar... but this does not work:

CustomButton = {

1: function () {
  alert("Just testing 1"+document.location.href);
  },

}

except for the +document.location.href it's the exact demo code I got from the dev site...

Share Improve this question asked Jun 15, 2011 at 1:32 RyanRyan 10.1k23 gold badges68 silver badges103 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 3

You should note that in extension developing, document and window variables refers to the Host Browser not the browser that contains the web site. you should use

gBrowser.selectedTab

for getting current tab and then using

currentURI.host

for getting URL host also note that selectedTab returns a tab variable then you should get the window of that tab. then the whole code will be:

gBrowser.getBrowserForTab(gBrowser.selectedTab).currentURI.host

Do you want to get the location of current document or the string that is in the location bar?

For location of current document

content.location.href

For the string in location bar

document.getElementById("urlbar").value

or

gURLBar.value

Those work for me, what context are you using it/how are you calling the function?

 > document.location.href
 < "http://stackoverflow./questions/6352035/firefox-addon-javascript-get-url-from-bar"

You can also use window.location.href

 > window.location.href
 < "http://stackoverflow./questions/6352035/firefox-addon-javascript-get-url-from-bar"

Try alert("The current page URL is " + browser.currentURI.spec) and see how that goes for you.

See also:

Firefox extension development : Get URL of new tab and https://developer.mozilla/en/XPCOM_Interface_Reference/nsIURI

Took a while to figure it all out:

gBrowser.currentURI.spec;

is how you do it.

Here's some code you may find useful

window.addEventListener('load', function (e) {

  var href = gBrowser.currentURI.spec;

  if ( href.match(/website./) ) {

    var contentDoc = content.document;
    // Do some stuff to the current website.'s DOM

  }

}, true);

本文标签: Firefox addonjavascript get url from barStack Overflow