如何在不重新加载页面的情况下通过JavaScript使用alert显示更改的浏览器URL
要在浏览器中更改URL而不加载新页面,我们可以使用JavaScript中的 history.pushState()方法 和replaceState()方法 。为了在更改URL之前显示浏览器URL,我们将在alert()函数中使用 window.location.href,并在更改浏览器URL之后再次使用。
注意: history.pushState()方法结合了HTML 5 History和JavaScript pushState()方法。
语法:
alert(" Message:" + window.location.hrf);
下面的示例说明了上述方法:
示例1
<head>
<script>
function geeks() {
alert("The current URL of this"
+ " page is: " + window.location.href);
}
function change_url() {
window.history.pushState("stateObj",
"new page", "changedURL.html");
alert("The URL of this page is: "
+ window.location.href);
}
</script>
</head>
<body onload="geeks()">
<a href="javascript:change_url()">
Click to change url
</a>
</body>
输出:
示例2
<head>
<script type="text/javascript">
function geeks() {
alert("The current URL of this "
+ "page is: " + window.location.href);
}
function change_url() {
window.history.replaceState("stateObj",
"new page", "changedURL.html");
alert("The URL of this page is: "
+ window.location.href);
}
</script>
</head>
<body onload="geeks()">
<a href="javascript:change_url()">
Click to change url
</a>
</body>
输出: