Get the current URL with JavaScript?
To get the current URL in JavaScript, the property window.location.href
is your friend:
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'shttp:
orhttps:
.hostname
: It's the domain name, likestackoverflow.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:
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.
Displaying URL information: Say it loud!
To display the URL in your document, you can do:
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:
URL structure: The road map
Here's the anatomy of a URL that would help you in your web development journey:
Was this article helpful?