JavaScript

JavaScript is a high-level, interpreted programming language that is widely used for web development. Initially designed as a client-side scripting language, it runs directly in web browsers, enabling dynamic and interactive user experiences. JavaScript can now be used for server-side development as well.

JavaScript Window Location

14 April 2025 | Category:

The window.location object in JavaScript is used to get or change the current URL of the browser. It plays a key role in redirecting pages, reloading, and navigating through different parts of a website.


📌 What is window.location?

  • It is a property of the window object.
  • It holds information about the current URL.
  • It also provides methods to redirect or reload the page.
console.log(window.location);

You can also just use location because window is global.


🔹 Common location Properties

PropertyDescriptionExample Output
location.hrefThe full URLhttps://example.com/path?query=123
location.hostnameThe domain name onlyexample.com
location.pathnameThe path of the URL/path
location.protocolThe protocol used (http/https)https:
location.portThe port number (if any)80, 443, or empty
location.searchThe query string (after ?)?query=123
location.hashThe anchor part (after #)#section1

🔸 Example: Log URL Details

console.log("Full URL:", location.href);
console.log("Domain:", location.hostname);
console.log("Path:", location.pathname);
console.log("Protocol:", location.protocol);
console.log("Query String:", location.search);
console.log("Hash:", location.hash);

🔄 Changing the Page URL

You can use these to redirect the browser to a new page.

✅ location.href

location.href = "https://google.com"; // Redirect to Google

✅ location.assign()

location.assign("https://example.com"); // Also redirects

✅ location.replace()

location.replace("https://example.com"); 
// Redirects, but doesn't keep history (can't go back)

🔁 Reloading the Page

location.reload(); // Reloads the current page

You can also use location.reload(true) in older browsers to force reload from the server (not cache).


📍 Example Mini App: Redirect Button

<button onclick="goToPage()">Go to YouTube</button>

<script>
  function goToPage() {
    location.href = "https://youtube.com";
  }
</script>

✅ Summary

TaskCode Example
Get full URLlocation.href
Redirect to a pagelocation.href = "url"
Force redirectlocation.replace("url")
Reload the pagelocation.reload()
Get query stringlocation.search
Get page pathlocation.pathname