Get Current URL in JavaScript: window.location.href
Learn how to get the full current URL in JavaScript using window.location.href and document.URL. Capture on page load, parse parts like protocol, host, pathname, search, hash with examples and pitfalls.
How to get the current URL with JavaScript?
I need to retrieve the full, current website URL using JavaScript, not a URL from a link. When the page loads, I want to capture the complete URL and store it in a variable for further processing.
Use window.location.href to get the full, current website URL in JavaScript — it returns the complete address (protocol, host, path, query string and hash). To capture it when the page loads and store it in a variable, read window.location.href inside a load handler (or immediately if your script runs after the DOM), for example: const currentUrl = window.location.href;.
Contents
- window location href — get the full current URL
- document URL in JavaScript and Location parts
- When to capture the URL on page load (DOMContentLoaded vs load)
- Examples: store, parse, and send the URL (javascript get url)
- Pitfalls, single‑page apps and security notes
- Sources
- Conclusion
window location href — get the full current URL
The simplest and most common way to get the current URL in JavaScript is window.location.href. It returns the full URL shown in the address bar as a string (e.g., https://example.com/path/page.html?a=1#section). You can read it or assign it to a variable:
// simplest form
const currentUrl = window.location.href;
console.log(currentUrl); // e.g. "https://example.com/path?query=1#hash"
location.href is part of the browser’s Location interface. It’s read/write — reading it just returns the URL; assigning to it will navigate the browser to the new address. For the formal definition and compatibility details see the Location.href docs on MDN: https://developer.mozilla.org/en-US/docs/Web/API/Location/href. W3Schools also documents this property and shows simple examples: https://www.w3schools.com/jsref/prop_loc_href.asp.
If you only need the URL string (not navigation), prefer reading window.location.href or window.location.toString(). document.URL usually returns the same string, but window.location is the standard choice because the location object provides convenient parts you can read separately.
document URL in JavaScript and Location parts
Sometimes you want parts of the URL rather than the whole thing. The location object exposes those pieces directly:
location.protocol— “https:”location.host— “example.com:8080”location.hostname— “example.com”location.port— “8080”location.pathname— “/path/page.html”location.search— “?a=1&b=2”location.hash— “#section”location.origin— “https://example.com” (modern browsers)
You can reconstruct the full URL from parts, but location.href already contains everything:
const fullFromParts =
window.location.origin +
window.location.pathname +
window.location.search +
window.location.hash;
document.URL is another way to get the document’s URL as a string; see an explanation and comparisons at GeeksforGeeks: https://www.geeksforgeeks.org/how-to-get-the-current-url-in-javascript/ and Tutorialspoint: https://www.tutorialspoint.com/how-to-get-the-current-url-with-javascript. Use these parts when you want a specific bit — for example location.search for query parameters or location.hash for fragments.
When to capture the URL on page load (DOMContentLoaded vs load)
Where and when you read window.location.href matters only if your script might run before the browser sets the address (rare) or if you depend on other DOM tasks finishing. Common patterns:
- If your script is at the end of
<body>, you can readwindow.location.hrefimmediately. - To be safe in the head or external scripts, wait for DOM ready:
document.addEventListener('DOMContentLoaded', () => {
const currentUrl = window.location.href;
// use currentUrl
});
- If you want to wait for all resources (images, iframes), use
window.onload:
window.addEventListener('load', () => {
const currentUrl = window.location.href;
});
Which event to use? Want the URL ASAP? Use DOMContentLoaded. Need every resource loaded? Use load. For most uses (analytics, parsing query params), DOMContentLoaded is fine.
Examples: store, parse, and send the URL (javascript get url)
Store the URL in a variable for later processing:
// capture on DOM ready and store globally (avoid globals in large apps)
document.addEventListener('DOMContentLoaded', () => {
const currentUrl = window.location.href;
// send to analytics, or parse parameters
// example: parse query params with URL API
const url = new URL(currentUrl);
const utm = url.searchParams.get('utm_source');
console.log({ currentUrl, utm });
});
Send the URL to a server:
fetch('/log-url', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({ url: window.location.href })
});
Parsing query strings and working with parameters is easier with the URL API (supported in modern browsers). For quick tutorials and examples see freeCodeCamp: https://www.freecodecamp.org/news/how-to-get-the-current-url-in-javascript/ and DelftStack: https://www.delftstack.com/howto/javascript/javascript-get-current-url/.
If you need to keep the URL in a form field (for tracking), set the value of a hidden input when the page loads.
Pitfalls, single‑page apps and security notes
A few things people trip over:
- Setting
location.hrefnavigates the page — don’t assign it unless you want to redirect. - Single‑page apps change the address with
history.pushState();window.location.hrefreflects the current address bar, but if you want to react to pushState calls you’ll need to hook into your router or listen forpopstate. - On the server (Node.js)
windowis undefined — checktypeof window !== 'undefined'before accessing it. - If your page uses a
<base>tag, relative URL resolution can change, butlocation.hrefstill shows the address bar URL. - URLs often contain characters that need encoding — when sending or storing, use
encodeURIComponentas appropriate.
For typical browser pages, window.location.href is reliable and widely supported (see MDN for the standard behavior: https://developer.mozilla.org/en-US/docs/Web/API/Location/href).
Sources
- GeeksforGeeks: How to get the current URL in JavaScript?
- W3Schools: Window Location href Property
- MDN: Location.href - Web APIs
- freeCodeCamp: How to Get the Current URL in JavaScript
- TutorialsPoint: How to get the current URL with JavaScript?
- Educative: How to get the current URL in JavaScript
- JavaTpoint: How to get current URL in JavaScript
- DelftStack: JavaScript Get Current URL
- SitePoint: How to Get the Current URL in JavaScript
- Stack Overflow: Get the current URL with JavaScript
- Programiz: JavaScript Program to Get Current URL
Conclusion
For a reliable, full current URL in the browser use window.location.href (or document.URL for a simple read-only string). Capture it on DOMContentLoaded if you need it as soon as the DOM is ready, store it in a variable, and use the Location parts or the URL API to parse/query it further. window.location.href is the straightforward answer when you need to get current URL in JavaScript.