Get or Change Current URL with window.location

In JavaScript, the window.location object lets you get the current page URL or redirect the browser to a different page. It's one of the easiest and most powerful ways to work with URLs in your web applications.

In this article, you'll learn how to get, set, and change URLs using window.location, with clear examples and practical use cases.


 What is window.location?

window.location is a built-in JavaScript object that contains information about the current URL. You can also use it to navigate to a different page.


 Get the Current URL

   let currentUrl = window.location.href;
   console.log(currentUrl);

What it does:
This prints the full current URL (including protocol, domain, path, etc.).


 Other Useful window.location Properties

You can access specific parts of the URL:

PropertyDescriptionExample Output
hrefFull URLhttps://example.com/page?x=10
protocolProtocol usedhttps:
hostnameDomain nameexample.com
pathnamePath after domain/page
searchQuery string?x=10
hashAnchor (if any)#section2







 
Example:
console.log("Protocol:", window.location.protocol);
console.log("Path:", window.location.pathname);
console.log("Query:", window.location.search);

Change the URL (Redirect)

You can redirect the user to another page using window.location.href:

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

What it does:
Takes the user to the new URL, just like clicking a link.


Use window.location.assign()

window.location.assign("https://example.com");
  • Works like setting href

  • Adds the new page to the browser history (user can go back)


 Use window.location.replace()

    window.location.replace("https://example.com");
  • Also redirects, but does not keep the current page in the history

  • Good for login/logout flows or preventing users from going back


 Reload the Page

  window.location.reload();
  • Reloads the current page (like pressing the refresh button)

  • Optional: window.location.reload(true) forces a reload from the server (some browsers may ignore this)


 Common Use Cases

  • Redirect users after login or logout

  • Get query parameters from the URL

  • Navigate between pages in a single-page app (SPA)

  • Refresh the page after a specific action


Summary

The window.location object gives you full control over the browser's address bar. You can read the current URL, change it, or reload the page easily — making it an essential tool for any web developer.

 Key Points:

  • Use window.location.href to get or change the URL

  • Use assign() to redirect with history

  • Use replace() to redirect without history

  • Use reload() to refresh the page