android-logo

JavaScript Window Location


The Location object represents a documents current location (URL). Because the window object is at the top of the scope chain, the window.location objects attributes may be accessed without using window.


Obtaining the URL of the Current Page

To access the URL of the current page, use the window.location.href property.


<!DOCTYPE html>
<html lang="en">
<body>
    <script>
    function fetchURL() {
        alert("Page URL : " + window.location.href);
    }
    </script>
     
    <button type="button" onclick="fetchURL();">Current Page URL</button>
</body>
</html>  


Get protocoldocument.write(window.location.protocol)
Get path namedocument.write(window.location.pathname)
Get hostnamedocument.write(window.location.hostname)
Get hostname with portdocument.write(window.location.host)
Get port numberdocument.write(window.location.port)
Get query stringdocument.write(window.location.search)
Get fragment identifierdocument.write(window.location.hash)
Get complete URLdocument.write(window.location.href)

Load New page

We use assign() and replace() method to load a different resource from a parameterized URL.


// Using assign() method
<script>
function newPage() {
    window.location.assign("https://www.androidaura.com/javascript");
}
</script>
 
<button type="button" onclick="newPage();">Load New Page</button>

// Using replace() method
<script>
function newPage() {
    window.location.replace("https://www.androidaura.com/javascript");
}
</script>
 
<button type="button" onclick="newPage();">Load New Page</button>


previous-button
next-button