How to get the current url with javascript

Posted on

You can get the current URL of a webpage using JavaScript by accessing the window.location object. This object contains various properties that can be used to retrieve different parts of the URL. To get the full URL, you can use window.location.href, which returns a string representing the entire URL of the current page. Additionally, window.location has other properties such as protocol, host, pathname, search, and hash that can be used to get specific parts of the URL. For instance, window.location.protocol returns the protocol (e.g., "http:"), and window.location.pathname returns the path (e.g., "/path/to/page"). Using these properties, you can manipulate and analyze the URL as needed in your JavaScript code.

Accessing the Current URL

To retrieve the current URL in JavaScript, you primarily use the window.location object. The href property of this object is especially useful because it provides the complete URL of the page. This is particularly handy when you need the entire URL for tasks such as logging, analytics, or navigation purposes. Here’s a basic example of how to use it:

const currentUrl = window.location.href;
console.log(currentUrl);

This simple script logs the full URL to the console. Understanding this is fundamental for tasks involving URL manipulation and navigation within your web applications.

Breakdown of window.location Properties

Protocol: The protocol property gives you the protocol of the current URL, such as "http:" or "https:". This is useful for determining the security context of the page.

const protocol = window.location.protocol;
console.log(protocol); // Outputs "http:" or "https:"

Host: The host property includes both the hostname and the port number (if specified), allowing you to identify the server that the page is hosted on.

const host = window.location.host;
console.log(host); // Outputs something like "www.example.com:80"

Hostname: If you only need the hostname without the port, you can use the hostname property.

const hostname = window.location.hostname;
console.log(hostname); // Outputs something like "www.example.com"

Pathname: The pathname property gives you the path of the URL, which is the part of the URL that follows the host (excluding query strings and hash fragments).

const pathname = window.location.pathname;
console.log(pathname); // Outputs something like "/path/to/page"

Search: This property contains the query string part of the URL, including the question mark.

const search = window.location.search;
console.log(search); // Outputs something like "?query=123"

Hash: The hash property gives you the fragment identifier, which is the part of the URL that follows the hash mark (#).

const hash = window.location.hash;
console.log(hash); // Outputs something like "#section1"

Practical Uses of URL Properties

URL Navigation: You can use these properties to navigate to different parts of your site. For instance, you can change the URL’s hash to navigate to a specific section of a page.

window.location.hash = "section2";

Query String Parameters: Extracting query string parameters can be useful for tracking user actions or handling page-specific configurations.

const params = new URLSearchParams(window.location.search);
const queryValue = params.get('query');
console.log(queryValue); // Outputs the value of the "query" parameter

Security Checks: Checking the protocol can help enforce security measures. For instance, you can redirect users to the HTTPS version of a site if they are on HTTP.

if (window.location.protocol !== "https:") {
    window.location.href = "https://" + window.location.host + window.location.pathname;
}

Dynamic Content Loading: By examining the hash, you can load different content dynamically without reloading the page, which is a common technique in single-page applications (SPAs).

window.addEventListener('hashchange', function() {
    const sectionId = window.location.hash.substring(1); // Remove the leading #
    loadSection(sectionId);
});

In summary, the window.location object is a powerful tool in JavaScript for working with URLs. It provides a comprehensive set of properties to access and manipulate different parts of the URL, enabling you to perform a wide range of tasks, from navigation and dynamic content loading to security checks and query parameter handling. By mastering these properties, you can enhance the interactivity and functionality of your web applications, ensuring a smoother and more responsive user experience.

👎 Dislike