Using Javascript in a Firefox add-on to get what is currently entered in the url string

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

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

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

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

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

Any help would be greatly appreciated. Thanks!

Edit: If there is no way to get the contents of the URL string before the user presses the enter button, is it possible to β€œintercept” what they typed after pressing the enter key?

+4
source share
4 answers

You cannot connect to what is entered in the address bar until the user sends it. When a user sends text, you have two options:

+2
source

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

This works, like gURLBar.value .

The question is in what context are you running this code. You must run this code in the browser.xul overlay and after loading the browser DOM .

In addition, yes, you can intercept what the user entered after pressing the enter key, but there is no public API for this, so you will need to find out how the corresponding code works in Firefox and replace the part that is responsible for Processing Enter in the location bar. [edit] see Firefox addon to do something every time a user presses Enter in the address bar

+1
source

getElementById gets the DOM element with the specified identifier. The address bar is not a DOM element.

Do you want to:

 var url = window.location; 
0
source

The closest thing to what you want is window.location.href . However, this is not an ideal accessor for what is in the URL text field, as you will find that entering text in the URL field, but not pressing enter will not change window.location.href . As far as I know, there is no direct access to the text value.

0
source

All Articles