Display Webpage current URL with Firefox extension

2019-06-05 10:03发布

I've written the following code for the purpose of the title of the post but instead of having the real URL I get the previous URL (e.g. If I'm on Google and type "car" in the search field and type "Enter" I get "http://www.google.fr" and not the URL from the search).

code :

window.addEventListener("change", function() { myExtension_with_change.init(); }, false);

var myExtension_with_change = {
   init: function() {
       var url = window.location.href;
       alert(url);
}

}

4条回答
beautiful°
3楼-- · 2019-06-05 10:24

In my case, I followed the recommendation in http://forums.mozillazine.org/viewtopic.php?f=9&t=194671. Simply calling the following code snippet gives me the current url

gBrowser.mCurrentBrowser.currentURI.QueryInterface(Components.interfaces.nsIURI);
var currentUrl = gBrowser.mCurrentBrowser.currentURI.spec;

查看更多
来,给爷笑一个
4楼-- · 2019-06-05 10:27

You might need to add an event listener inside the first to wait for the window to load, such as:

window.addEventListener("change", function()
{

   window.addEventListener("load", function()
   {

       myExtension_with_change.init();

   }, false);

}, false);
查看更多
迷人小祖宗
5楼-- · 2019-06-05 10:29

I doubt that window is the correct anchor to listen for changes of the URL. My first try would be listen to change events at #urlbar (I didn't try that, though):

window.getElementById('#urlbar').addEventListener("change", function() {    
    myExtension_with_change.init(); }, false);

If your ultimate goal is to listen to URL changes on every tab I suggest you also have look at the Tabbed Browser documentation and this code snippet on location changes.

查看更多
登录 后发表回答