如何在不重新加载页面的情况下使用JavaScript修改URL
方法1: 使用 replaceState() 方法替换当前状态
浏览器的历史接口管理浏览器会话历史记录。它包括在当前页面所在的标签或框架中访问的页面。通过操作这个状态,可以在不重新加载页面的情况下改变浏览器的URL。
replaceState() 方法用于修改当前历史记录条目,并使用传递的参数替换状态的属性。
此方法的参数分为三个部分,状态对象是关于状态的可序列化对象,标题是新状态的标题,URL是新状态的URL。
通过将所需的URL作为字符串传递给此方法,可以更改页面的URL而不重新加载页面。
示例:
<!DOCTYPE html>
<html>
<head>
<title>
How to modify URL without reloading
the page using JavaScript?
</title>
</head>
<body>
<h1 style="color: green">
GeeksForGeeks
</h1>
<b>
How to modify URL without reloading
the page using JavaScript?
</b>
<p>
Click on the button below to modify
the current history state
</p>
<button onclick="modifyState()">
Modify history state
</button>
<script>
function modifyState() {
let stateObj = { id: "100" };
window.history.replaceState(stateObj,
"Page 3", "/page3.html");
}
</script>
</body>
</html>
输出:
- 点击按钮之前:
- 点击按钮之后:
方法2:使用pushState()方法添加新状态
pushState()方法用于添加一个新的历史记录条目,通过传递的参数来改变当前URL,而不重新加载页面。
这个方法的参数有三个部分:状态对象是关于状态的可序列化对象,标题是状态的新标题,URL是状态的新URL。
通过将需要的URL作为字符串传递给此方法,可以更改URL,而不重新加载页面。
示例:
<!DOCTYPE html>
<html>
<head>
<title>
How to modify URL without reloading
the page using JavaScript?
</title>
</head>
<body>
<h1 style="color: green">
GeeksForGeeks
</h1>
<b>
How to modify URL without reloading
the page using JavaScript?
</b>
<p>
Click on the button below to add
a new history state
</p>
<button onclick="addState()">
Add history state
</button>
<script>
function addState() {
let stateObj = { id: "100" };
window.history.pushState(stateObj,
"Page 2", "/page2.html");
}
</script>
</body>
</html>
输出:
- 在点击按钮之前:
- 在点击按钮之后: