如何使用Js修改URL而不重新加载页面

作者: xusx 分类: JavaScript 发布时间: 2022-05-08 16:48 浏览:975

HTML5 History API 无疑是现代网站的必由之路。它完成了手头的任务,同时还提供了额外的功能。你可以使用 history.pushState()history.replaceState() 在浏览器中修改 URL,这取决于你的需要:

示例代码1

// 当前 URL 为 https://xushanxiang.com/js-modify-url-without-reload.html

const nextURL   = 'https://xushanxiang.com/';
const nextTitle = '首页';
const nextState = { additionalInformation: '用JS更新URL' };

// 这将在浏览器的历史记录中创建一个新条目,而无需重新加载
window.history.pushState(nextState, nextTitle, nextURL);

// 这将替换浏览器历史记录中的当前条目,而无需重新加载
window.history.replaceState(nextState, nextTitle, nextURL);

这两个方法的参数是相同的,允许您传递一个定制的可序列化状态对象作为第一个参数,一个定制的标题(尽管目前大多数浏览器会忽略这个参数)和您想要在浏览器历史中添加/替换的URL。

请记住,History API只允许同源url(浏览器不会检查url是否存在),所以你不能导航到一个完全不同的网站(不能跨域)。

使用 window.history.back(), window.history.forward() 和  window.history.go(1) 方法来完成在用户历史记录中向后和向前的跳转。

您可以通过查看长度属性的值来确定的历史堆栈中页面的数量:

let numberOfEntries = window.history.length;
HTML5 引入了 history.pushState()history.replaceState() 方法,它们分别可以添加和修改历史记录条目。这些方法通常与 window.onpopstate 配合使用。
 
使用 history.pushState() 可以改变 referrer,它在用户发送 XMLHttpRequest 请求时在 HTTP 头部使用,改变 state 后创建的 XMLHttpRequest 对象的 referrer都会被改变。因为 referrer 是标识创建  XMLHttpRequest 对象时 this 所代表的 window 对象中 document 的 URL。

示例代码2

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

// 或

window.addEventListener('popstate', (event) => {
    console.log('location: ' + document.location + ', state: ' + JSON.stringify(event.state));
});

let stateObj = {
    foo: 'bar',
};

history.pushState(stateObj, '首页', '/');

题外话

window.location.href, location.assign()location.replace() 这几个 Location API 会重新加载页面,但仍然允许您修改当前URL。

如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!