Skip to main content

Archive

Show more

How To Get The Current Page Url With Javascript

how-to-get-current-page-url-with-javascript

How to get the current page URL with JavaScript

When working with web applications, it is often necessary to retrieve the current page's URL using JavaScript. This information can be useful for various purposes, such as tracking user navigation, dynamically generating links, or performing conditional logic based on the current URL. JavaScript offers several methods to obtain the current page URL. you can retrieve the complete URL of the page, including the protocol, domain, path, and any query parameters or fragments.

In this article, we will explore different approaches to retrieve the current page URL using JavaScript, providing you with the knowledge to enhance your web applications with dynamic URL handling.


01. Using "window.location.href"

var currentURL = window.location.href;
console.log(currentURL);

Output:

https://www.rustcodeweb.com/2021/07/how-to-get-current-page-url-with-javascript.html

In this method, you can directly access the window.location.href property, which returns the complete URL of the current page, including the protocol, domain, path, and any query parameters or fragments.



02. Using "document.URL"

var currentURL = document.URL.;
console.log(currentURL);

Output:

https://www.rustcodeweb.com/2021/07/how-to-get-current-page-url-with-javascript.html

Here, you can use the document.URL property to retrieve the current page's URL. It is similar to window.location.href and returns the complete URL of the page.



03. Using "document.location"

var currentURL = window.location.;
console.log(currentURL);

Output:

Location {ancestorOrigins: DOMStringList, href: 'https://www.rustcodeweb.com/2021/07/how-to-get-current-page-url-with-javascript.html', origin: 'https://www.rustcodeweb.com', protocol: 'https:', host: 'www.rustcodeweb.com', …}

This method allows you to access the window.location object, which contains information about the current URL. The window.location object provides properties such as href, protocol, host, pathname, and more, allowing you to extract specific parts of the URL if needed.



04. Using "document.baseURI"

var currentURL = document.baseURI;
console.log(currentURL);

Output:

https://www.rustcodeweb.com/2021/07/how-to-get-current-page-url-with-javascript.html

The document.baseURI property returns the base URL of the current document, which is typically the URL of the HTML file. It provides the same result as the other methods mentioned previously, giving you access to the complete URL of the current page.


Comments