在不刷新页面的情况下更改 URL

Change URL without refresh the page

我想在不刷新页面的情况下替换 url。

我需要更改:

https://example.com/en/step1

https://example.com/en/step2

怎么做?

更新

基于 Manipulating the browser history,将空字符串作为 pushState 方法(aka title)的第二个参数传递应该是安全的,以防止将来对该方法进行更改, 所以最好像这样使用 pushState:

history.pushState(null, '', '/en/step2');    

您可以在上述文章中阅读更多相关信息

原答案

像这样使用history.pushState

history.pushState(null, null, '/en/step2');

更新 2 以回答 Idan Dagan 的评论:

Why not using history.replaceState()?

来自MDN

history.replaceState() operates exactly like history.pushState() except that replaceState() modifies the current history entry instead of creating a new one

这意味着如果您使用 replaceState,是的,url 将被更改,但用户不能使用浏览器的后退按钮返回上一个。状态( 因为 replaceState 不会向历史记录添加新条目)并且不推荐并提供糟糕的用户体验。

更新 3 添加 window.onpopstate

因此,由于这个答案引起了您的注意,这里是有关操纵浏览器历史记录的附加信息,在使用 pushState 之后,您可以使用 window.onpopstate 检测 back/forward 按钮导航像这样:

window.onpopstate = function(e) {
    // ... 
};

因为 pushState 的第一个参数是一个对象,如果你传递一个 object 而不是 null,你可以在 onpopstate 中访问那个对象,这非常方便,方法如下:

window.onpopstate = function(e) {
    if(e.state) {
        console.log(e.state);
    }
};

更新 4 添加 Reading the current state:

当您的页面加载时,它可能有一个非空状态对象,您可以读取当前历史记录条目的状态,而无需使用 history.state [=105] 等待 popstate 事件=] 像这样:

console.log(history.state);

奖金:使用以下检查history.pushState支持:

if (history.pushState) {
  // \o/
}

当您使用函数时...

<p onclick="update_url('/en/step2');">Link</p>

<script>
function update_url(url) {
    history.pushState(null, null, url);
}
</script>