How to get the current page URL in JavaScript?

In several times it may be needed to get the current web page URL from the client side. So in this tutorial, We are going to see how to get the current page URL in JavaScript. JavaScript code runs on the browser and it can detect the URL of the current page.

Print content from a particular div element using jQuery

The Location href Property of JavaScript can return the entire URL of the current page. Below is the given code of JavaScript location href property which will return the full URL of current page:


And below is the code that will show the alert message that contains the URL of the current page:

var page_url = window.location.href;   // Returns the entire URL
alert("URL of this page is "+page_url);

Now suppose, we want to get the path of the current web page in JavaScript then there is another property that is called Location pathname Property. It will return the path only instead of returning the full URL of the page. Below is the code which will alert the path of the current web page:

var pathname = window.location.pathname;   // Returns path only
alert("Path of this page is "+pathname);

The Good thing about getting the URL and path of the current page using JavaScript is that it will do all the things on the client side which often make the process simple.

Locate the Geo-position of a visitor in JavaScript

Copy text to clipboard on click using JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *