The active URL on the web holds significance for various applications, such as analytics tracking, dynamic rendering, or establishing conditional logic that relies on the page's URL. JavaScript provides several methods and properties that assist developers in modifying the URL of the present webpage.
In this article, we will explore various methods for retrieving the current URL, alongside a comprehensive understanding of how to utilize these techniques through practical examples. By the end of this guide, you will be equipped with the knowledge to effortlessly obtain and work with URLs in your JavaScript applications.
What is a URL?
A URL, which stands for Uniform Resource Locator, serves as an identifier for a resource located on the internet. The configuration of a URL comprises several elements, including the protocol (either HTTP or HTTPS), the domain name, an optional port, along with the path, query parameters, and fragment identifier. For example, in the URL https://logic-practice.com/page?id=123#section1, "https" represents the protocol, "logic-practice.com" is the domain name, "/page" indicates the path, while "id=123" and "#section1" are classified as query parameters. The ability to define routing, dynamic content, and API endpoints via URLs is essential for the development of any server-side web application.
Understanding the window.location Object
Utilizing the window object to retrieve the current URL in JavaScript is among the most straightforward and commonly employed techniques. This object encompasses attributes that signify different parts of the URL and provides valuable properties for analyzing each segment of the existing document's URL.
Here are important properties of window.location method:
- window.location.href: Returns a string containing the whole URL.
- window.location.protocol: Provides the protocol (e.g., http: or https:).
- window.location.hostname: Return domain name of the url (logic-practice.com).
- window.location.port: Gives the port number if present (e.g. 8080).
- window.location.pathname: Gives the path of the url e.g. ( /about-us ).
- window.location.search: Gives the query string, beginning with ? (e.g.,? id=123).
- window.location.hash: Gives the fragment identifier, preceded with a hash # (i.e., #section1).
Example: Getting the Full URL
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Get Current URL</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f4f4f9;
}
.container {
text-align: center;
background: #ffffff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
button {
background-color: #007bff;
color: #ffffff;
border: none;
padding: 10px 20px;
border-radius: 5px;
font-size: 16px;
cursor: pointer;
transition: background-color 0.3s;
width: 300px;
}
button:hover {
background-color: #0056b3;
}
.output {
margin-top: 20px;
font-size: 16px;
color: #333333;
font-weight: 600;
}
</style>
</head>
<body>
<div class="container">
<h1>Get Current URL</h1>
<button id="getUrlButton">Show Current URL</button>
<div class="output" id="urlOutput"></div>
</div>
<script>
document
.getElementById("getUrlButton")
.addEventListener("click", function () {
const currentUrl = window.location.href;
document.getElementById("urlOutput").textContent = `${currentUrl}`;
});
</script>
</body>
</html>
Output:
Browser:
Program’s Output:
Example: Extracting Individual Parts of the URL
You can utilize various attributes of the window.location object to retrieve particular components of the URL:
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Get Current URL Details</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f4f4f9;
}
.container {
text-align: center;
background: #ffffff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
button {
background-color: #007bff;
color: #ffffff;
border: none;
padding: 10px 20px;
border-radius: 5px;
font-size: 16px;
cursor: pointer;
transition: background-color 0.3s;
}
button:hover {
background-color: #0056b3;
}
table {
margin: 20px auto 0;
border-collapse: collapse;
width: 100%;
max-width: 600px;
}
table,
th,
td {
border: 1px solid #dddddd;
}
th,
td {
padding: 8px 12px;
text-align: left;
}
th {
background-color: #f4f4f9;
font-weight: bold;
}
</style>
</head>
<body>
<div class="container">
<h1>Get Current URL Details</h1>
<button id="getUrlButton">Show URL Details</button>
<table id="urlDetailsTable" style="display: none">
<thead>
<tr>
<th>Property</th>
<th>Value</th>
</tr>
</thead>
<tbody id="urlDetailsBody"></tbody>
</table>
</div>
<script>
document
.getElementById("getUrlButton")
.addEventListener("click", function () {
const urlDetails = [
{ property: "Protocol", value: window.location.protocol },
{ property: "Hostname", value: window.location.hostname },
{
property: "Port",
value: window.location.port || "(none specified)",
},
{ property: "Pathname", value: window.location.pathname },
{
property: "Query String",
value: window.location.search || "(none specified)",
},
{
property: "Hash",
value: window.location.hash || "(none specified)",
},
];
const tableBody = document.getElementById("urlDetailsBody");
tableBody.innerHTML = "";
urlDetails.forEach((detail) => {
const row = document.createElement("tr");
row.innerHTML = `<td>${detail.property}</td><td>${detail.value}</td>`;
tableBody.appendChild(row);
});
document.getElementById("urlDetailsTable").style.display = "table";
});
</script>
</body>
</html>
Output:
Browser:
Program’s Output:
Using the document.URL Property
A simple method to retrieve the complete URL is by utilizing the document.URL property. This property returns the entire URL of the active document in the form of a string.
Example:
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Get Full URL</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f4f4f9;
}
.container {
text-align: center;
background: #ffffff;
width: 300px;
padding: 20px;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
button {
background-color: #007bff;
color: #ffffff;
border: none;
padding: 10px 20px;
border-radius: 5px;
font-size: 16px;
cursor: pointer;
transition: background-color 0.3s;
}
button:hover {
background-color: #0056b3;
}
.output {
margin-top: 20px;
font-size: 16px;
color: #333333;
word-wrap: break-word;
max-width: 600px;
font-weight: 600;
}
</style>
</head>
<body>
<div class="container">
<h1>Get Full URL</h1>
<button id="getFullUrlButton">Show Full URL</button>
<div class="output" id="fullUrlOutput"></div>
</div>
<script>
document
.getElementById("getFullUrlButton")
.addEventListener("click", function () {
const fullUrl = document.URL;
document.getElementById("fullUrlOutput").textContent = `${fullUrl}`;
});
</script>
</body>
</html>
Output:
Browser:
Program’s Output:
This approach is straightforward; nevertheless, it is generally not preferred because the window location object provides a wider array of options and encompasses additional properties for managing the URL.
Practical Use Cases for Getting the Current URL
- Analytics Tracking: Track the current URL to understand user behaviour and page visits.
- Conditional Rendering: Components rendered based on the URL or query params.
- Dynamic Content Loading: Dynamically fetch and display content based on the url.
- SEO Optimization: Ensure proper URL structure for better search engine indexing.
- URL Redirection: Redirect to another page based on conditions.
Example: Redirecting Based on URL Path
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Pathname Checker</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f4f4f9;
}
.container {
text-align: center;
background: #ffffff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
button {
background-color: #007bff;
color: #ffffff;
border: none;
padding: 10px 20px;
border-radius: 5px;
font-size: 16px;
cursor: pointer;
transition: background-color 0.3s;
}
button:hover {
background-color: #0056b3;
}
.output {
margin-top: 20px;
font-size: 16px;
color: #333333;
word-wrap: break-word;
max-width: 600px;
font-weight: 600;
}
</style>
</head>
<body>
<div class="container">
<h1>Pathname Checker</h1>
<button id="checkPathnameButton">Check Current Pathname</button>
<div class="output" id="pathnameOutput"></div>
</div>
<script>
document
.getElementById("checkPathnameButton")
.addEventListener("click", function () {
const pathname = window.location.pathname;
const output = document.getElementById("pathnameOutput");
if (pathname === "/login") {
output.textContent = "User is on the login page.";
} else {
output.textContent = "User is not on the login page.";
}
});
</script>
</body>
</html>
Output:
Browser:
Program’s Output:
Conclusion
Retrieving the current URL in JavaScript is an essential skill that aids in the development of dynamic, interactive, and user-oriented web applications. You can utilize various approaches, such as the window location method, the document URL method, or the contemporary URL interface. Each of these methods offers distinct advantages and specific scenarios where they excel. Mastering these tools can significantly enhance the quality of your web application in the long run.