JavaScript Window Location
The window.location object is an essential part of the Browser Object Model (BOM). It provides information about the document's current location (the URL) and provides methods to redirect the user to a new location.
Understanding Properties
Rather than manually parsing strings to find the domain or the query parameters, window.location breaks the URL down into easily accessible properties:
- href: The entire URL (
https://example.com:8080/path?query=1#hash) - protocol: The web protocol used (
https:) - hostname: The domain name of the server (
example.com) - pathname: The path after the domain (
/path) - search: The query string, starting with a question mark (
?query=1) - hash: The anchor/fragment identifier, starting with a hash (
#hash)
Redirecting Methods
When building single-page applications or handling authentication, you frequently need to move the user to a different page dynamically.
The location.assign("url") method loads a new document. Crucially, it saves the current page in the session history, meaning the user can click the browser's "Back" button to return.
Conversely, location.replace("url") replaces the current document. It removes the current URL from the document history, preventing the user from using "Back" to navigate to the original document. This is highly recommended for security redirects (like after a logout).
Parsing Query Strings
Historically, reading the location.search property required complex RegEx or string splitting. Today, JavaScript provides the native URLSearchParams interface. By passing the search string into it, you get an iterable object that easily grabs values via params.get('key').
View Full Transcript+
This section contains the full detailed transcript of the video lessons regarding window.location, BOM hierarchy, and safe redirect patterns. It covers the nuanced difference between window.location.href assignment versus the assign() and replace() methods.
