How to Get Current URL in JavaScript: Simple Guide
You can get the current URL in JavaScript using
window.location.href. This property returns the full URL of the current page as a string.Syntax
The syntax to get the current URL is simple:
window.location.href: Returns the full URL of the current page as a string.
javascript
const currentUrl = window.location.href;Example
This example shows how to get and display the current URL in the browser console.
javascript
const currentUrl = window.location.href; console.log('Current URL:', currentUrl);
Output
Current URL: https://example.com/page
Common Pitfalls
Some common mistakes when getting the current URL include:
- Using
document.URLwhich also works but is less common. - Trying to get the URL before the page fully loads, which may cause unexpected results.
- Confusing
window.location.hrefwith otherwindow.locationproperties likepathnameororigin.
javascript
/* Wrong way: expecting pathname gives full URL */ console.log(window.location.pathname); // Outputs only path, not full URL /* Right way: use href for full URL */ console.log(window.location.href);
Quick Reference
Here is a quick summary of useful window.location properties:
| Property | Description | Example Output |
|---|---|---|
| href | Full URL of the current page | https://example.com/page?query=1 |
| protocol | Protocol part of the URL | https: |
| host | Hostname and port | example.com:443 |
| hostname | Hostname only | example.com |
| port | Port number | 443 |
| pathname | Path after the host | /page |
| search | Query string including '?' | ?query=1 |
| hash | Fragment identifier including '#' | #section1 |
Key Takeaways
Use window.location.href to get the full current URL as a string.
window.location has many parts; href gives the complete URL.
Avoid using pathname or other parts if you want the full URL.
Make sure the page is loaded before accessing the URL for accurate results.