Open In App

How to get the current URL using JavaScript ?

Last Updated : 29 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will know about getting the Website URL for the current webpage or website. The current URL can be obtained by using the ‘URL’ property of the Document object which contains information about the current URL. The ‘URL’ property returns a string with the full location of the current page, along with containing the string having the HTTP protocol such as ( http://).

We can get the current URL using Javascript in two ways:

Document.URL: The DOM URL property in HTML is used to return a string that contains the complete URL of the current document. The string also includes the HTTP protocol such as ( http://).

Syntax:

document.URL

Return Value: It returns a string value that represents the full URL of the document. 

Example 1: This example illustrates to get the current URL of the webpage.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>
        How to get the current URL using JavaScript ?
    </title>
</head>
  
<body>
    <h1 style="color:green">GeeksforGeeks</h1>
    <h2>
        JavaScript: Program to
        get the website URL ?
    </h2>
    <p>
        <b>
            Click on Below Button
            To Get Current URL
        </b>
    </p>
  
    <button onclick="GetURL()">
         Get URL 
    </button>
    <p id="url"></p>
  
  
    <script>
        function GetURL() {
            var gfg = document.URL;
            document.getElementById("url").innerHTML = gfg;
        }
    </script>
</body>
  
</html>


Output:

How to get the current URL using JavaScript ?

How to get the current URL using JavaScript ?

window.location.href: HTML DOM Window.location property returns a Location object that contains information about the current location of the document.

Syntax:

window.location.href

Example 2: This example illustrates to get the current URL of the webpage.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>
        How to get the current URL using JavaScript ?
    </title>
</head>
  
<body>
    <h1 style="color:green">
        GeeksforGeeks
    </h1>
    <h2>
        JavaScript: Program to
        get the website URL ?
    </h2>
    <p>
        <b>
            Click on Below Button
            To Get Current URL
        </b>
    </p>
  
    <button onclick="GetURL()"
        Get URL 
    </button>
    <p id="url"></p>
  
    <script>
        function GetURL() {
            var gfg = window.location.href;
            document.getElementById("url").innerHTML = gfg;
        }
    </script>
</body>
  
</html>


Output:

How to get the current URL using JavaScript ?

How to get the current URL using JavaScript ?



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads