How to get the current URL in JavaScript
Answer: Using window.location.href property
JavaScript offers several methods to get the current URL of the webpage. But there is one thing common in all the methods that all methods use location object, which is the property of the window object. The window.object provides the current page address or URL and redirects the browser to a new page.
We can get the current address or URL of the web page using the window.location.href property, including all the components.
Example
In the given example, we have used the window.location.href property to get the address of the current page with JavaScript.
Using document.documentURI property
The document.documentURI is used to set or return the location of the document as a string. If the document was created by using the DocumnetImplementation object or if it is undefined, then the return value is null. We can also get the current URL of the page using this property.
Example: Using document.documentURI property
In this example, we can get the current URL using the document.documentURI property.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Get current URL in JavaScript</title>
</head>
<body>
<p id="url"></p>
<script>
document.getElementById("url").textContent = document.documentURI;
</script>
</body>
</html>
Output
https://www.studytonight.com/code/playground/web/?id=KCkS9r
Using document.URL property
We can also get the current URL using the document.URL property. This is a read-only property of the document interface which returns the URL of the document as a string.
Example: Using document.URL property
In the given example, we have used the document.URL property to get the current URL of the document.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Get current URL in JavaScript</title>
</head>
<body>
<p id="url"></p>
<script>
document.getElementById("url").textContent = document.URL;
</script>
</body>
</html>
Output
https://www.studytonight.com/code/playground/web/?id=KCkS9r
Conclusion
In this lesson, we have discussed how to get the URL (current address) of the webpage. In JavaScript, we can get the URL of the current webpage using the window.location.href, document.documentURI, and document.URL properties. The address of the current page includes hostname, query-string, fragment identifier, etc.