views:

170

answers:

4

I'm writing a Firefox add-on and trying to get what is currently typed into the address bar, but every time I try, I get a null error. The code I'm using is

var url = document.getElementById("urlbar").value;

However, when I do that, the error I get is

Error on line 1: document.getElementById("urlbar") is null`.

I have a blank tab open with text written into the address bar. This is in firefox 3.6.9 .

Any help would be appreciated. Thanks!

Edit: If there is no way to get the contenets of the url bar, before the user presses enter, is it possible to "intercept" what they typed after they press enter?

A: 

getElementById gets a DOM element with the specified ID. The address bar isn't a DOM element.

You want:

var url = window.location;
Michael Shimmins
It sounds like the OP is wanting the content of the address bar, which could be something the user hasn't submitted yet. window.location will return the url of the page loaded in the browser.
rchern
rchen is correct with this assumption. I pretty much want to intercept what the user types in so when they press enter, I reformat what they typed into something more appropriate.
Daniel
-1, no longer relevant.
Nickolay
A: 

The closest thing to what you want is window.location.href. However, it's not a perfect accessor for what is in the URL text box, as you will find that typing into the URL box but not pressing "enter" will not modify window.location.href. As far as I know, there is no way to access the text value directly.

bcherry
+2  A: 

You can't hook into what is typed in the address bar until the user submits it. Once the user submits text, you have two options:

  1. If you're writing an extension, you can hook into an event when the url changes
  2. Use window.location.href to pull the url of the page loaded in the browser.
rchern
+1  A: 

var url = document.getElementById("urlbar").value;

That works, as does gURLBar.value.

The question is what context you run that code in. You should be running that code in a browser.xul overlay and after the browser DOM is loaded.

Also, yes it's possible to intercept what the user typed after they press enter, but there's not a public API for that, so you'd have to figure out how the relevant code in Firefox work and replace the part that's responsible for handling Enter in the location bar. [edit] see http://stackoverflow.com/questions/3704364/firefox-addon-to-do-something-everytime-a-user-hits-enter-in-the-address-bar

Nickolay