简体   繁体   English

在Firefox扩展上使用Javascript动态获取网页的URL

[英]Get URL of a webpage dynamically with Javascript on a Firefox extension

I'd like to get the URL of a webpage dynamically (ie if the url changes get the new url) using Javascript with a Firefox extension. 我想使用带有Firefox扩展的Javascript动态获取网页的URL(即,如果URL更改获得新的URL)。

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 ) 显示带有Firefox扩展名的网页当前URL

Can someone post some code to show me a way to achieve this please ? 有人可以发布一些代码来向我展示实现此目标的方法吗?

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栏中添加一个事件侦听器(我在一条注释中解释了为什么旧问题​​的答案中的代码不起作用),但是坦率地说,这不是最好的方法。 URL bar contents can also change if the user starts typing into it for example. 例如,如果用户开始输入,URL栏内容也可以更改。 And the user could even choose to remove the URL bar from the browser window. 用户甚至可以选择从浏览器窗口中删除URL栏。

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 . 您可以在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). 您将对onLocationChange方法的调用感兴趣,这将在每次需要更改URL栏内容时发生(也包括用户在选项卡之间切换时)。

You could try listening to the hashchange event on window object. 您可以尝试监听window对象上的hashchange事件。 Both chrome and firefox support it. chrome和firefox都支持它。 Not sure about IE though. 虽然不确定IE。

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/ . 如果您的浏览器不支持“ hashchange”事件,则可以使用此插件http://benalman.com/projects/jquery-hashchange-plugin/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM