The window.location object is one of the most useful parts of the Browser Object Model (BOM). It allows you to get the address (URL) of the current page, and if needed, redirect the browser to a completely new page.
Below are the specific parts of the URL for the page you are currently viewing:
.href --
.hostname --
.pathname --
.protocol --
You can access individual segments of a URL using different properties of the location object.
// Get the full URL
console.log(window.location.href);
// Get the domain name (hostname)
console.log(window.location.hostname);
// Get the file path (pathname)
console.log(window.location.pathname);
// Get the web protocol (http: or https:)
console.log(window.location.protocol);
window.screen, you can omit the window. prefix and simply use location.href.
The location object provides methods to move the user to a different address or refresh the current one.
The assign() method loads a new document. This behaves exactly like clicking a link.
function goToHome() {
window.location.assign("https://redohub.com");
}
Assigning a string to location.href has the same effect as assign().
window.location.href = "https://redohub.com";
To refresh the current page, use the reload() method.
// Reloads the page
window.location.reload();
location.assign() over directly changing href when you want to make your intent (navigating) clear in your code.
| Property/Method | Description |
|---|---|
location.href |
Returns the entire URL of the current page |
location.hostname |
Returns the domain name of the web host |
location.pathname |
Returns the path and filename of the current page |
location.protocol |
Returns the web protocol (http: or https:) |
location.port |
Returns the port number (e.g., 80 or 443) |
location.assign() |
Loads a new document (navigates to a URL) |
location.replace() |
Replaces the current document (no history entry) |
location.replace() is different from assign() because it removes the current page from the browser's history. The user cannot use the "Back" button to return to it.
window.location or simply location..assign("url") to navigate while keeping the back button functional..replace("url") to navigate and disable the back button for that step.