我想我会在 Fabio 和 Aram 的答案中添加一些内容。我想我有时可能想在 url 中保留哈希。但通常不会,所以我将该参数设置为默认为false
.
replaceState
仍然没有在 Chrome 上设置页面标题。所以我添加了几行来更改标题,如果提供的话。
function insertUrlParam(key, value, title = '', preserve_hash = false) {
if (history.pushState) {
let searchParams = new URLSearchParams(window.location.search);
searchParams.set(key, value);
let newurl = window.location.protocol + "//" + window.location.host + window.location.pathname
+ '?' + searchParams.toString();
if(preserve_hash) newurl = newurl + window.location.hash;
let oldTitle = document.title;
if(title !== '') {
window.history.replaceState({path: newurl}, title, newurl);
if(document.title !== title) { // fallback if above doesn't work
document.title = title;
}
} else { // in case browsers ever clear titles set with empty string
window.history.replaceState({path: newurl}, oldTitle, newurl);
}
}
}