In JavaScript, the window.location
read-only property returns a Location
object that represents the current URL of the document being displayed in that window.
The Location
object can be used to get the current page URL, navigate to a new page, reload the current page, get different parts of the URL (hostname, protocol, etc.), and much more.
The following example demonstrates how the window.location.href
property can be used to get the entire URL of the current web page:
const url = window.location.href;
console.log(url);
// https://attacomsian.com/blog/javascript-location-object/
Since
window
is the global object representing the window in which the script is running, you can access theLocation
object with it. For example, thewindow.location.href
can be written aslocation.href
.
Similarly, you can use other properties of the Location
object such as host
, hostname
, port
, protocol
, pathname
, search
, and hash
to access different parts of the URL:
// Get hostname with port (localhost or localhost:8080)
console.log(location.host);
// Get hostname (localhost or www.domain.com)
console.log(location.hostname);
// Get protocol (http or https)
console.log(location.protocol);
// Get port number (8080)
console.log(location.port);
// Get pathname (/javascript-tutorials/)
console.log(location.pathname);
// Get query string (?q=object)
console.log(location.search);
// Get URL fragment identifier (#trending)
console.log(window.location.hash);
Besides the above mentioned properties, the Location
object also provides several methods such as assign()
, reload()
, and replace()
to manipulate the current URL:
// Load new URL
location.assign(`https://attacomsian.com`);
// Reload the current URL
location.reload();
// Load new URL with session history
location.replace(`https://youtube.com`);
// Print complete URL (same as location.href)
location.toString();
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.