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
console.log(window.location.href); // e.g., "https://www.example.com/path?name=value"
- Navigating to a new page (redirection)
window.location.href = 'https://www.newwebsite.com';
- Checking the domain name
console.log(window.location.hostname); // e.g., "www.example.com"
- Refreshing the current page
window.location.reload();
The window.location
object can be used to view or change the URL of the current page, or navigate to a new URL.
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help