Open In App

How to Get the Current URL using JavaScript?

Last Updated : 17 Nov, 2024
Comments
Improve
Suggest changes
1 Like
Like
Report

Here are two different methods to get the current URL in JavaScript.

1. Using Document.URL Property

The DOM URL property in HTML is used to return a string that contains the complete URL of the current document. The string also includes the HTTP protocol such as ( http://).

Syntax

document.URL

Return Value: It returns a string value that represents the full URL of the document. 

<script>
// Get the current URL using document.URL
let currentUrl = document.URL;

// Log the URL to the console
console.log(currentUrl);
</script>

Output

http://127.0.0.1:5500/index.html

2. Using window.location.href Property

The window.location.href property of the HTML DOM Window object returns a string containing the URL of the current page. This property is part of the Location object, which contains information about the current location of the document.

Syntax

window.location.href
<script>
// Get the current URL using document.URL
let currentUrl = document.URL;

// Log the URL to the console
console.log(currentUrl);
</script>

Output:

http://127.0.0.1:5500/index.html

Note: Use the HTML file to copy paste and run the given code and you can see the output in the console, it will print the URL.



Next Article

Similar Reads