Get the Current Page URL With JavaScript

You can use the window.location.href property to get the current page URL with JavaScript.

This returns the entire URL of the page.

Here's a simple example:

const currentPageUrl = window.location.href;
console.log(currentPageUrl); // will output something like: ""

You can get a lot of properties from the window.location that might be useful if you plan to do something with that URL.

Here's a list of properties and what they do:

hash - The fragment identifier, used to identify a portion of the document. Example output: "#section2"

host - The hostname and port of the URL. Example output: ""

hostname - The domain name of the URL. Example output: ""

href - Represents the entire URL. Example output: ""

origin - The protocol, hostname, and port number. Example output: ""

pathname - The URL's path section comes after the host. Example output: "/path/index.html"

port - The port number of the URL. Example output: "8080"

protocol - The protocol scheme of the URL. Example output: "https:"

search - The part of the URL that follows the '?' symbol. Example output: "?section=test"

Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.


Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.