如何使用 JavaScript 检测地址栏更改?
我有一个 Ajax 重型应用程序,可能有一个 URL,例如
http://example.com/myApp/#page=1
当用户操作站点时,地址栏可以更改为类似的内容,而
http://example.com/myApp/#page=5
无需重新加载页面。
我的问题是以下序列:
- 用户为第一个 URL 添加了书签。
- 用户操纵应用程序使得第二URL是当前状态。
- 用户单击步骤 1 中创建的书签。
- 地址栏中的 URL 从 http:// 更改example.com/myApp/#page=5 到 http://example.com/ myApp/#page=1,但我不知道如何检测发生的更改。
如果我检测到变化,一些 JavaScript 就会对其采取行动。
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
without reloading the page.
My problem is the following sequence:
- 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.
If I detect a change some JavaScript would act on it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
HTML5 引入了一个 hashchange 事件,该事件允许您注册 url 哈希更改的通知,而无需使用计时器轮询它们。
所有主要浏览器(Firefox 3.6、IE8、Chrome、其他基于 Webkit 的浏览器)都支持它,但我仍然强烈建议使用一个为您处理事件的库 - 即在不支持的浏览器中使用计时器HTML5 事件并以其他方式使用该事件。
有关该活动的更多信息,请参阅 https://developer.mozilla.org/en/dom /window.onhashchange 和 http:// msdn.microsoft.com/en-us/library/cc288209%28VS.85%29.aspx。
HTML5 introduces a hashchange event which allows you to register for notifications of url hash changes without polling for them with a timer.
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.
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.
使用 setTimeout/interval 定期检查当前地址:
check the current address periodically using setTimeout/interval:
您应该扩展位置对象以公开可以绑定到的事件。
IE:
You should extend the location object to expose an event that you can bind to.
ie:
SWFaddress 是此类内容的优秀库。
SWFaddress is an excellent library for these types of things.