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
-
location.href
: Retrieves or sets the full URL of the current page. (e.g., https://www.example.com/path?name=value) -
location.protocol
: Indicates the protocol of the current URL. (e.g., http: or https:) -
location.hostname
: Refers to the domain name of the current URL. (e.g., www.example.com) -
location.pathname
: Shows the path part of the current URL. (e.g., /path) -
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) -
location.reload()
: Method to refresh the current page.
Code Examples
- Check the URL of the current page
JavaScript
console.log(window.location.href);
// Example: "https://www.example.com/path?name=value"
- Navigate (redirect) to a new page
JavaScript
window.location.href = 'https://www.newwebsite.com';
- Check the domain name
JavaScript
console.log(window.location.hostname);
// Example: "www.example.com"
- 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.