Get URL of a webpage dynamically with Javascript o

2019-08-31 23:41发布

I'd like to get the URL of a webpage dynamically (i.e if the url changes get the new url) using Javascript with a Firefox extension.

So far I've tried to use an event listener attached to the current window but it doesn't work. ( Display Webpage current URL with Firefox extension )

Can someone post some code to show me a way to achieve this please ?

2条回答
老娘就宠你
2楼-- · 2019-08-31 23:46

You could add an event listener to the URL bar (I explained in a comment why the code in the answer to your old question didn't work) but frankly - this isn't the best way. URL bar contents can also change if the user starts typing into it for example. And the user could even choose to remove the URL bar from the browser window.

The best way to achieve this is implementing a progress listener. You can find example code and explanation on https://developer.mozilla.org/en/Code_snippets/Progress_Listeners. You would be interested in calls to the onLocationChange method, that will happen every time the URL bar contents need to change (also when the user switches between tabs).

查看更多
何必那么认真
3楼-- · 2019-09-01 00:09

You could try listening to the hashchange event on window object. Both chrome and firefox support it. Not sure about IE though.

window.onhashchange = function () {
    hashChanged(window.location.hash);
}

If your browser doesn't support "hashchange" event, you could use this plugin http://benalman.com/projects/jquery-hashchange-plugin/ .

查看更多
登录 后发表回答