更改URL而不刷新页面 [英] Change URL without refresh the page
问题描述
我想在不刷新页面的情况下替换网址.
I would like to replace an url without page refresh.
我需要更改:
https://example.com/en/step1
到
https://example.com/en/step2
该怎么做?
推荐答案
更新
基于操纵浏览器历史记录,并传递空白字符串作为 pushState
方法( aka title )的第二个参数应该可以防止将来对该方法的更改,因此最好像这样使用 pushState
:
Based on Manipulating the browser history, passing the empty string as second parameter of pushState
method (aka title) should be safe against future changes to the method, so it's better to use pushState
like this:
history.pushState(null, '', '/en/step2');
您可以在上述文章中了解更多有关内容
原始答案
像这样使用 history.pushState
:
history.pushState(null, null, '/en/step2');
- 更多信息( MDN文章):我可以使用
- 也许您应该看看@ Internet Explorer是否支持pushState和replaceState?
更新2 来回答 Idan Dagan 的评论:
为什么不使用
history.replaceState()
?
来自 MDN
history.replaceState()的操作与history.pushState()完全相同,不同之处在于replaceState()会修改当前历史记录条目,而不是创建新的历史记录条目
history.replaceState() operates exactly like history.pushState() except that replaceState() modifies the current history entry instead of creating a new one
这意味着,如果您使用 replaceState
,是的,URL将被更改,但用户无法使用浏览器的后退"按钮返回到上一个.状态(,因为 replaceState
不会在历史记录中添加新条目),因此不建议使用它,并提供不良的UX.
That means if you use replaceState
, yes the url will be changed but user can not use Browser's Back button to back to prev. state(s) anymore (because replaceState
doesn't add new entry to history) and it's not recommended and provide bad UX.
更新3 以添加 window.onpopstate
Update 3 to add window.onpopstate
因此,正如这个答案引起您的注意一样,以下是有关操纵浏览器历史记录的其他信息,在使用 pushState
后,您可以使用 window.onpopstate来检测后退/前进按钮的导航.
像这样:
So, as this answer got your attention, here is additional info about manipulating the browser history, after using pushState
, you can detect the back/forward button navigation by using window.onpopstate
like this:
window.onpopstate = function(e) {
// ...
};
由于 pushState
的第一个参数是一个对象,如果传递了 object
而不是 null
,则可以在 onpopstate
十分方便,方法如下:
As the first argument of pushState
is an object, if you passed an object
instead of null
, you can access that object in onpopstate
which is very handy, here is how:
window.onpopstate = function(e) {
if(e.state) {
console.log(e.state);
}
};
更新4 以添加读取当前状态:
页面加载时,它可能具有非空状态对象,您可以使用 history.state <来读取当前历史记录条目的状态,而无需等待
popstate
事件./code>这样的属性:
When your page loads, it might have a non-null state object, you can read the state of the current history entry without waiting for a popstate
event using the history.state
property like this:
console.log(history.state);
奖金:使用以下命令检查 history.pushState
支持:
Bonus: Use following to check history.pushState
support:
if (history.pushState) {
// \o/
}
这篇关于更改URL而不刷新页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!