JavaScript — Get the Current URL

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

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!


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.