How to Get the Current URL with JavaScript

How to Get the Current URL with JavaScript

When building web applications, it’s often necessary to get the current URL of the page. This is useful for various reasons, such as tracking user behavior, implementing dynamic functionality, and more. In this article, we’ll explore different ways to get the current URL using JavaScript.

Using the window.location Object

The most common way to get the current URL is by using the window.location object. This object provides information about the current URL, such as the protocol, hostname, port, path, query string, and more. Here’s an example:

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

In this example, we’re accessing the href property of the window.location object, which returns the full URL of the current page. We then log this URL to the console.

You can also access other properties of the window.location object to get specific parts of the URL. For example:

const protocol = window.location.protocol; // "http:" or "https:"
const hostname = window.location.hostname; // "example.com"
const port = window.location.port; // "8080"
const path = window.location.pathname; // "/path/to/page"
const query = window.location.search; // "?foo=bar"
const hash = window.location.hash; // "#section1"

By combining these properties, you can build custom URLs or extract specific information from the current URL.

Using the Document Object

Another way to get the current URL is by using the document object. This object provides information about the current document, such as the URL, title, and more. Here’s an example:

const currentUrl = document.URL;
console.log(currentUrl);

In this example, we’re accessing the URL property of the document object, which returns the full URL of the current page. We then log this URL to the console.

You can also access other properties of the document object to get specific parts of the URL. For example:

const title = document.title; // "My Page Title"
const referrer = document.referrer; // "http://referrer.com"

Conclusion

Getting the current URL is a common task when working with web applications. By using the window.location and document objects, you can easily access information about the current URL and use it to implement dynamic functionality or track user behavior.