Getting Current URL: Difference between revisions
From MozillaZine Knowledge Base
Jump to navigationJump to search
(initial) |
m (added line break) |
||
(2 intermediate revisions by one other user not shown) | |||
Line 1: | Line 1: | ||
There are a variety of ways to get the current URL, depending upon the context in which your code is running: | There are a variety of ways to get the current URL, depending upon the context in which your code is running: | ||
Line 17: | Line 16: | ||
<pre> | <pre> | ||
function getURL() { | function getURL() { | ||
var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator); | var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]. | ||
getService(Components.interfaces.nsIWindowMediator); | |||
var recentWindow = wm.getMostRecentWindow("navigator:browser"); | var recentWindow = wm.getMostRecentWindow("navigator:browser"); | ||
return recentWindow ? recentWindow.content.document.location : null; | return recentWindow ? recentWindow.content.document.location : null; | ||
} | } | ||
</pre> | </pre> | ||
==Appendix== | |||
[[Category:Example code]] |
Latest revision as of 22:45, 17 July 2006
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; }