Explain Codes LogoExplain Codes Logo

Get the current URL with JavaScript?

javascript
prompt-engineering
location-object
url-manipulation
Alex KataevbyAlex Kataev·Sep 27, 2024
TLDR

To get the current URL in JavaScript, the property window.location.href is your friend:

console.log(window.location.href); // Prints the full URL

This approach is the most reliable and recommended way to reach your destination, the current URL, across various web browsers.

Hitting the URL bullseye: Specific components

Insight into URL components

Sometimes, you might need to hit the bullseye, i.e., one specific part of the URL. Here is your URL components guide:

  • protocol: It defines the communication rules. Mostly, it's http: or https:.
  • hostname: It's the domain name, like stackoverflow.com.
  • port: It's the door to the server, for example, 8080.
  • pathname: It's the hallway you're in, like /questions/ask.
  • search: It's the question you ask, starting ? like ?tag=javascript.
  • hash: It's the specific point you're looking at, starting # like #answer.

To get these components, you can use:

let protocol = window.location.protocol; // Let's talk rules! let hostname = window.location.hostname; // Hey there, domain! let port = window.location.port; // Door number, please! let pathname = window.location.pathname; // Which hallway are we in? let search = window.location.search; // Got any questions? let hash = window.location.hash; // Oh, looking for something specific?

URL manipulation: More than just the viewer

The Location object isn't just a passive observer. It's an active participant that enables you to edit the browser's URL or navigate to a different URL. Methods like assign(), replace(), and reload() are your tools.

When the URL changes: Staying alert

The URL can change without reloading the page, especially in Single Page Applications (SPAs). Using the popstate event, the window object can notify you when the URL has changed.

window.addEventListener('popstate', function(event) { console.log("So, we're moving!"); // URL adventure alert! });

Displaying URL information: Say it loud!

To display the URL in your document, you can do:

document.getElementById('urlDisplay').textContent = window.location.href; // I said it loud!

Ensure the document has an element with the id urlDisplay.

The tool belt: Various ways to get the URL

Separating the wheat from the chaff

For a combination of the protocol and host, you can use the compact tool window.location.origin instead of putting the strings together:

let origin = window.location.origin; // The best of both worlds!

URL structure: The road map

Here's the anatomy of a URL that would help you in your web development journey:

<protocol>//<hostname>:<port>/<pathname>?<search>#<hash>