Get Current URL Path of Web Page in JavaScript

I am going to show you how to get the current URL of the web page with the help of JavaScript on the client side.

We can use the JavaScript window.location object to get the current URL of the client’s web page.

Window Location Href Property

The window.location.href property of window.location object can return the current web page URL where a visitor is staying. 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 the 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 page URL.

Now below is our JavaScript code:

<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 selected our paragraph tag by its ID and set the HTML content with the innerHTML property. In our HTML content, we pass the variable that contains the 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 *