The window.location
object can be used to get the current page address (URL) and to redirect the browser to a new page.
The window.location
object can be written without the window prefix.
Some examples:
window.location.href
returns the href (URL) of the current pagewindow.location.hostname
returns the domain name of the web hostwindow.location.pathname
returns the path and filename of the current pagewindow.location.protocol
returns the web protocol used (http: or https:)window.location.assign()
loads a new documentThe window.location.href
property returns the URL of the current page.
Display the href (URL) of the current page:
document.getElementById("demo").innerHTML =
"Page location is " + window.location.href;
Result is:
The window.location.hostname
property returns the name of the internet host (of the current page).
Display the name of the host:
document.getElementById("demo").innerHTML =
"Page hostname is " + window.location.hostname;
Result is:
The window.location.pathname
property returns the pathname of the current page.
Display the path name of the current URL:
document.getElementById("demo").innerHTML =
"Page path is " + window.location.pathname;
Result is:
The window.location.protocol
property returns the web protocol of the page.
Display the web protocol:
document.getElementById("demo").innerHTML =
"Page protocol is " + window.location.protocol;
Result is:
The window.location.port
property returns the number of the internet host port (of the current page).
Display the name of the host:
document.getElementById("demo").innerHTML =
"Port number is " + window.location.port;
Result is:
Most browsers will not display default port numbers (80 for http and 443 for https)
The window.location.assign()
method loads a new document.
Load a new document:
<html>
<head>
<script>
function newDoc() {
window.location.assign("https://www.91xjr.com")
}
</script>
</head>
<body>
<input type="button" value="Load new document" onclick="newDoc()">
</body>
</html>
Try it Yourself »
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!