在不使用JavaScript加载新页面的情况下更改浏览器中的URL [英] Change the URL in the browser without loading the new page using JavaScript

查看:167
本文介绍了在不使用JavaScript加载新页面的情况下更改浏览器中的URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何获得可能对当前页面产生一些影响的 JavaScript 操作,但是还会更改浏览器中的URL,以便在用户点击重新加载或书签时使用新的URL?

How would I have a JavaScript action that may have some effects on the current page but would also change the URL in the browser so if the user hits reload or bookmark the new URL is used?

如果后退按钮会重新加载原始网址也会很好。

It would also be nice if the back button would reload the original URL.

我正在尝试记录URL中的JavaScript状态。

I am trying to record JavaScript state in the URL.

推荐答案

如果您希望它在不支持的浏览器中工作history.pushState history.popState 然而,旧方式是设置片段标识符,这不会导致页面重新加载。

If you want it to work in browsers that don't support history.pushState and history.popState yet, the "old" way is to set the fragment identifier, which won't cause a page reload.

基本思路是将 window.location.hash 属性设置为包含任何状态信息的值需要,然后使用 window.onhashchange事件,或者使用旧版浏览器不支持 onhashchange (IE< 8,Firefox< 3.6),定期检查哈希是否已更改(使用 setInterval 并更新页面。您还需要检查页面加载时的哈希值以设置初始内容。

The basic idea is to set the window.location.hash property to a value that contains whatever state information you need, then either use the window.onhashchange event, or for older browsers that don't support onhashchange (IE < 8, Firefox < 3.6), periodically check to see if the hash has changed (using setInterval for example) and update the page. You will also need to check the hash value on page load to set up the initial content.

如果您使用的是jQuery,那么 hashchange插件将使用浏览器支持的任何方法。我确定其他库也有插件。

If you're using jQuery there's a hashchange plugin that will use whichever method the browser supports. I'm sure there are plugins for other libraries as well.

要注意的一件事是在页面上与id冲突,因为浏览器会滚动到任何元素具有匹配的ID。

One thing to be careful of is colliding with ids on the page, because the browser will scroll to any element with a matching id.

这篇关于在不使用JavaScript加载新页面的情况下更改浏览器中的URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆