JavaScript Window Location
The window.location object is used to get the current page's address (URL) and redirect the browser to a new page.
Window Location
window.locationThis object can be written without the window prefix. Some examples:
Some examples:
- location.hostname returns the domain name of the web host
- location.pathname returns the path and filename of the current page
- location.port returns the port of the web host (80 or 443)
- location.protocol returns the web protocol used (http: or https:)
Window Location href
location.hrefThe property returns the URL of the current page.
Examples
Returns the entire URL (of the current page):
<script>
document.write(location.href);
</script>
document.write(location.href);
</script>
The output of the above code is:
Window Location pathname
location.pathnameThe property returns the path name of the URL.
Examples
Returns the path name of the current URL:
<script>
document.write(location.pathname);
</script>
document.write(location.pathname);
</script>
The output of the above code is:
Window Location assign
location.assign()The method loads a new document.
Examples
Load a new document:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example Tutorial (example.com)</title>
<script>
function newDoc(){
window.location.assign("https://www.example.com")
}
</script>
</head>
<body>
<input type="button" value="Load new document" onclick="newDoc()">
</body>
</html>
Try it yourself »