You can retrieve the current URL using JavaScript in the browser. The global window
object provides a window.location
attribute which contains all the parts of the current URL.
This tutorial shows you how to get the current browser URL in client-side JavaScript.
JavaScript Series Overview
- Get the Current URL
- Get URL Query Parameters
- How to Smooth Scroll to an HTML Element
- Sort a Set
- New, Immutable Array Methods
- Detect Network Error
- Create Array from AsyncIterable
- Using the new Array Grouping Methods
- Test for LocalStorage Support
- Get Battery Status
- Detect If a Device Battery Is Charging (Coming soon)
Retrieve the Current Browser URL
You can retrieve the browser’s URL by using window.location.href
:
const currentUrl = window.location.href
As described, the window.location
property represents a Location
interface and contains all parts of the current URL in different attributes. These attributes may be valuable for you, too.
Imagine you’re currently on this URL:
https://futurestud.io/tutorials?filter=video
Here are all the URL parts you’re receiving by window.location
:
const {
href, // "https://futurestud.io/tutorials?filter=video"
protocol, // "https:"
host, // "futurestud.io"
hostname, // "futurestud.io"
port, // ""
origin, // "https://futurestud.io"
pathname, // "/tutorials"
search, // "?key=value"
hash // ""
} = window.location
Enjoy!