document.URL returns the complete URL of the current document as a string.
const pageUrl = document.URL;
console.log(pageUrl);
window.location.href (usually shortened to location.href) also exposes the current address. The location object is especially useful when you need individual URL parts.
const currentUrl = document.URL;
The property name is case-sensitive: use URL, not url.
console.log(location.href); // complete address
console.log(location.origin); // scheme + host + port
console.log(location.hostname); // hostname only
console.log(location.pathname); // path
console.log(location.search); // query string
console.log(location.hash); // fragment
When you only need the host name, prefer location.hostname rather than the deprecated document.domain API. See the document.domain tutorial for legacy behavior.
The URL class is useful when you want a reusable object representing an address.
const url = new URL(document.URL);
console.log(url.hostname);
console.log(url.pathname);
console.log(url.searchParams.get("id"));
The original example used document.write(). For normal page output, write into an existing element instead:
const output = document.getElementById("urlOutput");
output.textContent = document.URL;
This avoids the parsing and page-replacement problems associated with document.write().
document.URL is a string; use new URL(...) if you need convenient parsing methods./, ?, or # when the URL API can parse it reliably.location.href navigates the browser; reading it does not.Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.