HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Window Location

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.


Current URL Inspector

Below are the specific parts of the URL for the page you are currently viewing:

.href --
.hostname --
.pathname --
.protocol --

Getting the URL Parts

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);
Note: Just like window.screen, you can omit the window. prefix and simply use location.href.

Redirecting and Loading Pages

The location object provides methods to move the user to a different address or refresh the current one.

Using location.assign()

The assign() method loads a new document. This behaves exactly like clicking a link.

function goToHome() {
    window.location.assign("https://redohub.com");
}

Using location.href

Assigning a string to location.href has the same effect as assign().

window.location.href = "https://redohub.com";

Using location.reload()

To refresh the current page, use the reload() method.

// Reloads the page
window.location.reload();
Tip: Prefer location.assign() over directly changing href when you want to make your intent (navigating) clear in your code.

Location Object Summary

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)
Important: 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.

Key Points to Remember

  • The Location object is used to read or change the browser's URL.
  • Access it via window.location or simply location.
  • Use .assign("url") to navigate while keeping the back button functional.
  • Use .replace("url") to navigate and disable the back button for that step.
  • The object is reactive — changing its properties immediately triggers navigation.