Get Current URL Path of Web Page in JavaScript

By Faruque Ahamed Mollick

I am going to show you how to get the current URL of the web page using JavaScript.

Getting the current URL in JavaScript is easy. We can use the JavaScript window.location object to get current URL of our web page.

 

Window Location Href Property

The window.location.href property of window.location object will return the current web page URL. We are going to see an example.

In our example, we will get our current page URL in JavaScript and then store it in a variable. After that, we will show the URL of our current page on the web page.

 



Show the current URL of the web page in JavaScript

Our current page URL will be shown in p tag which has an ID that you can see below:

<p id="currentURL"></p>

In above HTML code, we have taken the ID of our paragraph tag. We are going to use that ID in our JavaScript code to display the current page URL.

Now below is our JavaScript code that will get the current page URL and show it on our web page:

<script type="text/javascript">
   var currentURL = window.location.href;
   document.getElementById("currentURL").innerHTML = currentURL;
</script>

In the above code, we have put the current page URL in a variable “currentURL”. After that, we have we select our paragraph tag by its ID and set the HTML content with innerHTML property. In our HTML content, we pass the variable that contains the current page URL.

Now we can run our code.

Let’s try it yourself, run the code on your browser. If you run the code, you will be able to see the current page URL on the web page.

 

Also, read:

 

So in this post, we have learned how to get and display the current URL of web page in JavaScript.

Leave a Reply

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