Window - window.location
The window.location
object allows you to retrieve the URL of the current browser window and navigate the web page to a new URL.
Key Properties and Methods
-
location.href
: Gets 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
: Represents the domain name of the current URL. (e.g., www.example.com) -
location.pathname
: Signifies the path portion of the current URL. (e.g., /path) -
location.search
: Refers to the query string of the URL (the part after the ?). Query strings are used for transmitting search terms or data. (e.g., ?name=value) -
location.reload()
: A method for refreshing the current page.
Code Examples
- Checking the current page URL
JavaScript
console.log(window.location.href);
// e.g., "https://www.example.com/path?name=value"
- Navigating to a new page (redirection)
JavaScript
window.location.href = 'https://www.newwebsite.com';
- Checking the domain name
JavaScript
console.log(window.location.hostname);
// e.g., "www.example.com"
- Refreshing the current page
JavaScript
window.location.reload();
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.