开发者

Using Javascript in Firefox add-on to get what is currently typed into the url bar

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 th开发者_如何学Goe contents of the URL bar, before the user presses enter, is it possible to "intercept" what they typed after they press enter?


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.


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 Firefox addon to do something everytime a user hits Enter in the address bar


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

You want:

var url = window.location;


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜