JavaScript Window Location Object

The window.location object provides information about the current URL and enables navigation to other pages. It is part of the Browser Object Model (BOM) and acts as an interface to interact with the browser’s address bar.

Key Properties of window.location

  • href: Returns the full URL of the current page.
console.log(window.location.href); // e.g., "https://www.example.com/path"
  • hostname: Returns the domain name of the web host.
console.log(window.location.hostname); // e.g., "www.example.com"
  • pathname: Returns the path and file name of the current URL.
console.log(window.location.pathname); // e.g., "/path"
  • protocol: Returns the protocol used by the page (e.g., http: or https:).
console.log(window.location.protocol); // e.g., "https:"
  • port: Returns the port number used in the URL. If no port is specified, it returns an empty string.
console.log(window.location.port); // e.g., "443" for HTTPS
  • search: Returns the query string part of the URL, including the leading ?.
console.log(window.location.search); // e.g., "?id=123&name=test"
  • hash: Returns the anchor part of the URL (after #).
console.log(window.location.hash); // e.g., "#section1"

Methods of window.location

  • assign(url): Loads a new document at the specified URL.
window.location.assign("http://thecodingcollege.com");
  • reload(): Reloads the current page. Pass true to force a reload from the server.
window.location.reload(); // Reloads the page
window.location.reload(true); // Forces a server reload
  • replace(url): Replaces the current document with a new one without adding it to the browser history.
window.location.replace("https://www.example.com");
  • toString(): Returns the full URL as a string (implicitly used by href).
console.log(window.location.toString());

Practical Examples

  • Redirect Users Based on Conditions:
if (window.location.protocol !== "https:") {
    window.location.replace("https://" + window.location.hostname);
}
  • Extract Query Parameters:
const params = new URLSearchParams(window.location.search);
console.log(params.get("id")); // Retrieve the value of "id"
  • Navigate to a Section:
window.location.hash = "section2"; // Scrolls to the element with id="section2"
  • Check Current Domain:
if (window.location.hostname === "www.example.com") {
    console.log("Welcome to Example!");
}

Security Note

Manipulating window.location directly can make your site vulnerable to phishing or open redirect attacks. Always validate user input when constructing URLs dynamically.

Conclusion

The window.location object is a powerful tool for managing URLs and navigation within a web application. Understanding its properties and methods can help you create dynamic, responsive, and user-friendly web experiences.

For more coding insights and tutorials, visit The Coding College.

Leave a Comment