The Location object represents a documents current location (URL). Because the window object is at the top of the scope chain, the window.location objects attributes may be accessed without using window.
To access the URL of the current page, use the window.location.href property.
<!DOCTYPE html>
<html lang="en">
<body>
<script>
function fetchURL() {
alert("Page URL : " + window.location.href);
}
</script>
<button type="button" onclick="fetchURL();">Current Page URL</button>
</body>
</html>
Get protocol | document.write(window.location.protocol) |
Get path name | document.write(window.location.pathname) |
Get hostname | document.write(window.location.hostname) |
Get hostname with port | document.write(window.location.host) |
Get port number | document.write(window.location.port) |
Get query string | document.write(window.location.search) |
Get fragment identifier | document.write(window.location.hash) |
Get complete URL | document.write(window.location.href) |
We use assign() and replace() method to load a different resource from a parameterized URL.
// Using assign() method
<script>
function newPage() {
window.location.assign("https://www.techstackguru.com/javascript");
}
</script>
<button type="button" onclick="newPage();">Load New Page</button>
// Using replace() method
<script>
function newPage() {
window.location.replace("https://www.techstackguru.com/javascript");
}
</script>
<button type="button" onclick="newPage();">Load New Page</button>