Discover the different methods JavaScript offers to obtain the current URL that is open in the web browser.

To retrieve the current URL of the opened page using JavaScript, you can utilize the location property provided by the browser on the window object.

window.location

As window is the global object in the browser, you can reference the property as

location

This property returns a Location object that contains various properties of its own:

window.location

The current page URL can be accessed through

location.href

Additionally, the location object provides other useful information:

Code Description
location.hostname returns the hostname
location.origin returns the origin URL
location.hash returns the URL fragment identifier (the part after the # symbol)
location.pathname returns the path of the URL
location.port returns the port number of the URL
location.protocol returns the protocol of the URL (e.g., “http:” or “https:”)
location.search returns the query string of the URL (the part after the ? symbol)