Niall Maher1 min read

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: "https://www.example.com:8080/path/index.html?section=test#section2"

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: "www.example.com:8080"

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

href - Represents the entire URL. Example output: "https://www.example.com:8080/path/index.html?section=test#section2"

origin - The protocol, hostname, and port number. Example output: "https://www.example.com:8080"

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"

JavaScript

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.

Loading

Loading discussion...

Hey! 👋

Got something to say?

or to leave a comment.