Skip to main content
Practice

Window - window.location

The window.location object allows you to get information about the URL of the current browser window and navigate to a new URL.


Major Properties and Methods

  1. location.href: Retrieves or sets the full URL of the current page. (e.g., https://www.example.com/path?name=value)

  2. location.protocol: Indicates the protocol of the current URL. (e.g., http: or https:)

  3. location.hostname: Refers to the domain name of the current URL. (e.g., www.example.com)

  4. location.pathname: Shows the path part of the current URL. (e.g., /path)

  5. location.search: Refers to the query string of the URL (the part after ?). Query strings are used to pass search terms or data. (e.g., ?name=value)

  6. location.reload(): Method to refresh the current page.


Code Examples

  1. Check the URL of the current page
JavaScript
console.log(window.location.href);
// Example: "https://www.example.com/path?name=value"

  1. Navigate (redirect) to a new page
JavaScript
window.location.href = 'https://www.newwebsite.com';

  1. Check the domain name
JavaScript
console.log(window.location.hostname);
// Example: "www.example.com"

  1. Refresh the current page
JavaScript
window.location.reload();

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.