【问题标题】:Change URL without refresh the page [duplicate]在不刷新页面的情况下更改 URL [重复]
【发布时间】:2016-05-25 13:03:01
【问题描述】:

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

我需要改变:

https://example.com/en/step1

https://example.com/en/step2

怎么做?

【问题讨论】:

标签: javascript html5-history


【解决方案1】:

更新

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

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

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

原答案

像这样使用history.pushState

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

更新 2 回答 Idan Dagan 的评论:

为什么不使用history.replaceState()

来自MDN

history.replaceState() 的操作与 history.pushState() 完全相同,只是 replaceState() 修改当前历史条目而不是创建新条目

这意味着如果您使用replaceState,是的,url 将被更改,但用户不能使用浏览器的后退按钮返回到上一页。 state(s) 不再存在(因为 replaceState 不会向历史添加新条目)并且不建议这样做并提供糟糕的用户体验。

更新 3 以添加 window.onpopstate

因此,由于这个答案引起了您的注意,这里是有关操纵浏览器历史记录的附加信息,使用 pushState 后,您可以使用 window.onpopstate 检测后退/前进按钮导航,如下所示:

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

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

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

更新 4 添加Reading the current state

当您的页面加载时,它可能有一个非空状态对象,您可以读取当前历史记录条目的状态,而无需等待 popstate 事件使用 history.state 属性,如下所示:

console.log(history.state);

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

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

【讨论】:

  • 为什么不使用history.replaceState()?
  • @IdanDagan 我更新了答案以解释原因。编码愉快!
  • 注意:如果您在从 URL 中删除路径时遇到问题,请删除上述代码中路径开头的 /
【解决方案2】:

当你使用函数时...

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

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

【讨论】:

    猜你喜欢
    • 2020-10-31
    • 2017-03-24
    • 1970-01-01
    • 1970-01-01
    • 2020-10-04
    • 1970-01-01
    • 2013-07-07
    • 1970-01-01
    相关资源
    最近更新 更多