JavaScript Location
The location
object is a property of the global window
object. It provides information about the current URL and allows you to redirect or reload the page dynamically.
Key Topics
Location Properties
The location
object includes the following properties:
- href: The full URL of the current page.
- hostname: The domain name of the web host.
- pathname: The path of the current page.
- protocol: The protocol used (e.g.,
http:
orhttps:
). - port: The port number used by the web server.
- search: The query string of the URL.
console.log("Full URL:", location.href);
console.log("Hostname:", location.hostname);
console.log("Pathname:", location.pathname);
console.log("Protocol:", location.protocol);
console.log("Port:", location.port);
console.log("Query String:", location.search);
Output
> Full URL: [Current URL]
> Hostname: [Current Hostname]
> Pathname: [Current Path]
> Protocol: [http/https]
> Port: [Port Number]
> Query String: [Query String]
Explanation: The location
object properties allow you to access various parts of the current URL, making it useful for navigation and data extraction.
Location Methods
The location
object includes the following methods:
- assign(url): Loads a new document at the specified URL.
- reload(): Reloads the current page.
- replace(url): Replaces the current document with a new one at the specified URL (does not keep the current page in the history).
// Redirect to a new URL
location.assign("https://www.example.com");
// Reload the current page
location.reload();
// Replace the current page without saving in history
location.replace("https://www.example.com/newpage");
Explanation: Methods like assign
, reload
, and replace
are used to navigate or reload the page programmatically.
JavaScript Usage in DOM
Below is a DOM-based example demonstrating the use of the location
object to display and manipulate the current URL.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Location Example</title>
</head>
<body>
<p id="info"></p>
<button onclick="reloadPage()">Reload Page</button>
<button onclick="redirectToExample()">Redirect</button>
<script>
// Display current URL details
document.getElementById("info").textContent = `Full URL: ${location.href}`;
// Reload the page
function reloadPage() {
location.reload();
}
// Redirect to another URL
function redirectToExample() {
location.assign("https://www.example.com");
}
</script>
</body>
</html>
Key Takeaways
- URL Management: The
location
object provides easy access to URL components and allows navigation. - Reload and Redirect: Use methods like
reload
andassign
to reload or redirect pages. - URL Components: Extract components like hostname, pathname, and query string for programmatic use.
- Dynamic Navigation: The
location
object simplifies dynamic redirection and URL updates.