如何修改URL而不重新加载页面?

发布时间 2023-10-30 22:33:11作者: 小满独家

内容来自 DOC https://q.houxu6.top/?s=如何修改URL而不重新加载页面?

有没有办法在不重新加载页面的情况下修改当前页面的URL?

如果可能的话,我想访问#哈希之前的部分。

我只需要更改域名之后的部分,所以它不像是违反了跨域政策。

  window.location.href = "www.mysite.com/page2.php"; // 这个会重新加载页面

现在可以在Chrome、Safari、Firefox 4+和Internet Explorer 10pp4+中实现!

有关更多信息,请查看此问题的解答:更新地址栏的新URL而不带哈希或重新加载页面

示例:

 function processAjaxData(response, urlPath){
     document.getElementById("content").innerHTML = response.html;
     document.title = response.pageTitle;
     window.history.pushState({"html":response.html,"pageTitle":response.pageTitle},"", urlPath);
 }

然后可以使用window.onpopstate来检测后退/前进按钮导航:

window.onpopstate = function(e){
    if(e.state){
        document.getElementById("content").innerHTML = e.state.html;
        document.title = e.state.pageTitle;
    }
};


有关更深入地了解操作浏览器历史记录的内容,请参阅此MDN文章