Getting Current URL

From MozillaZine Knowledge Base
Revision as of 18:11, 6 December 2005 by Grimholtz (talk | contribs) (initial)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigationJump to search

Getting Current URL

There are a variety of ways to get the current URL, depending upon the context in which your code is running:

window.location.href
window.opener.location.href
gURLBar.value

The "brute force" method always works, but isn't necessarily the most efficient. This code always returns the URL of the most recently used browser, so it isn't sufficient if you need to get the URL of a background browser.

function getURL() {
  var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator);
  var recentWindow = wm.getMostRecentWindow("navigator:browser");
  return recentWindow ? recentWindow.content.document.location : null;
}