如何使用JavaScript检测地址栏更改? [英] How can I detect an address bar change with JavaScript?
问题描述
我有一个Ajax繁重的应用程序,可能有一个URL,例如
I have a Ajax heavy application that may have a URL such as
http://example.com/myApp/#page=1
当用户操作网站时,地址栏可以更改为
When a user manipulates the site, the address bar can change to something like
http://example.com/myApp/#page=5
没有重新加载页面。
我的问题是以下顺序:
- 用户为第一个URL添加书签。
- 用户操纵应用程序,使第二个URL成为当前状态。
- 用户点击在步骤1中创建的书签。
- 地址栏中的URL更改为 http://example.com/myApp/#page=5 转到 http://example.com/myApp/#page=1 ,但我不知道有办法检测发生的变化。
- A user bookmarks the first URL.
- The user manipulates the application such that the second URL is the current state.
- The user clicks on the bookmark created in step 1.
- The URL in the address bar changes from http://example.com/myApp/#page=5 to http://example.com/myApp/#page=1, but I don't know of a way to detect the change happened.
如果我发现了变化一些JavaScript会对它采取行动。
If I detect a change some JavaScript would act on it.
推荐答案
HTML5引入了一个 hashchange 事件,允许您注册url哈希更改的通知,无需使用计时器进行轮询。
HTML5 introduces a hashchange event which allows you to register for notifications of url hash changes without polling for them with a timer.
它受所有主流浏览器支持(Firefox 3.6,IE8,Chrome,其他基于Webkit的浏览器),但我仍然强烈建议使用一个处理事件的库 - 即在不支持HTML5事件的浏览器中使用计时器,否则使用事件。
It it supported by all major browsers (Firefox 3.6, IE8, Chrome, other Webkit-based browsers), but I'd still highly suggest to use a library which handles the event for you - i.e. by using a timer in browsers not supporting the HTML5 event and using the event otherwise.
有关该活动的更多信息,请参阅 https://developer.mozilla.org/en/ dom / window.onhashchange 和 http:/ /msdn.microsoft.com/en-us/library/cc288209%28VS.85%29.aspx 。
For further information on the event, see https://developer.mozilla.org/en/dom/window.onhashchange and http://msdn.microsoft.com/en-us/library/cc288209%28VS.85%29.aspx.
这篇关于如何使用JavaScript检测地址栏更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!