Accessing website URL and path in JAVAScript

If you want to know what the current URL user have visited in browser in your Javascript code, so you can perform some operations like we did in our another post “How to hide code / Div based on contents in URL using Javascript ?” where we tried to hide a button only on specific URL.

Know the current visited webpage complete URL

 var URL = window.location.href;

example : for the current page, it will print as “https://www.lynxbee.com/accessing-website-url-and-path-in-javascript/”

Get the path after domain for your visited webpage

var urlPath = window.location.pathname;

Example: for the current web page, it will print as “/accessing-website-url-and-path-in-javascript/”

Get the domain name of your visited webpage

var domainName = window.location.hostname;

Example: For the current web page, it will print as “https://www.lynxbee.com/”

Get the protocol of your visited webpage

var protocol = window.location.protocol;

Example : For the current webpage, it will print as, “https:”

The complete code can be written as below,

<html>
  <head>
    <script>
    window.onload = function() {

        html = "The complete URL of this web page is: "
        var URL = window.location.href;
        console.log(URL);
        html += URL;
        html += "<br> </br>"

        html += "The complete URL of this web page is: "
        var urlPath = window.location.pathname;
        console.log(urlPath);
        html += urlPath;
        html += "<br> </br>"

        html += "The complete URL of this web page is: "
        var domainName = window.location.hostname;
        console.log(domainName);
        html += domainName;
        html += "<br> </br>"

        html += "The protocol of this web page is: "
        var protocol = window.location.protocol;
        console.log(protocol);
        html += protocol;
        html += "<br> </br>"

        document.getElementById("h1ElementId").innerHTML = html;
    }
    </script>
  </head>
  <body>
  <h1 id="h1ElementId"></h1>
  </body>
</html>

Leave a Comment