Skip to main content

Window Location href

The window.location object provides information about the URL of the current page or the URL of a new page to be loaded.

This object contains several properties and methods that can be used to get or set various parts of the URL, such as the protocol, hostname, pathname, search parameters, and hash fragment.

Here are some of the most commonly used properties of the window.location object:

  • location.href: returns the complete URL of the current page, including the protocol, hostname, port number, pathname, search parameters, and hash fragment.
  • location.protocol: returns the protocol used by the current page (e.g., "http:", "https:", "file:", etc.). location.hostname: returns the hostname of the current page (e.g., "www.example.com").
  • location.pathname: returns the pathname of the current page, including any subdirectories and the file name.
  • location.search: returns the search parameters of the current page, including the "?" character.
  • location.hash: returns the hash fragment of the current page, including the "#" character.

An example of how to use the location.href property:

const url = window.location.href;
console.log(`The URL of the current page is ${url}`);

In this example:

  • The href property is accessed on the location object to get the complete URL of the current page, and the result is logged to the browser console using the console.log() method.

You can also use the location.assign() method to load a new page or URL, like this:

window.location.assign("https://www.example.com");

In this example:

  • The assign() method is called on the location object to load a new page with the URL "https://www.example.com".
  • This method is equivalent to clicking on a link or typing a URL in the browser address bar.