Open In App

JavaScript | window.location and document.location Objects

window.location and document.location: These objects are used for getting the URL (the current or present page address) and avert browser to a new page or window. The main difference between both is their compatibility with the browsers.

All modern browsers map document.location to the window.location but you can prefer window.location for cross-browser safety.



Syntax:

Example 1: This example using different properties to get different parts of URL.




<!DOCTYPE html>
<html lang="en">
  
<head>
    <title>Get Different Part of a URL</title>
</head>
  
<body>
    <script>
  
        // Prints complete URL
        document.write("URL IS:  " 
                + window.location.href + "<br>");
  
        // Prints hostname like local host (www.example.com)
        document.write("HOSTNAME:  " 
                + window.location.hostname + "<br>");
  
        // Prints pathname like /products/find.php
        document.write("PATHNAME:  " 
                + window.location.pathname + "<br>");
  
        // Prints the protocol used like http: or https:
        document.write("PROTOCOL:  " 
                + window.location.protocol + "<br>");
  
        // Prints hostname with port like localhost:3000
        document.write("HOSTNAME WITH PORT:  " 
                + window.location.host + "<br>");
  
        // Prints port number like 3000
        document.write("PORTNUMBER:  " 
                + window.location.port + "<br>");
    </script>
</body>
  
</html>

Output:



URL IS: https://ide.geeksforgeeks.org/tryit.php
HOSTNAME: ide.geeksforgeeks.org
PATHNAME: /tryit.php
PROTOCOL: https:
HOSTNAME WITH PORT: ide.geeksforgeeks.org
PORTNUMBER:

Note: When you visit a specific website, it is always connected to a port. However, most browsers will not display the default port number.

Example 2: Assign or load new document.




<!DOCTYPE html>
<html lang="en">
  
<head>
    <title>
        Load another Resource or 
        document from a URL
    </title>
  
    <script>
        function loadPage() {
            window.location.assign(
                "https://ide.geeksforgeeks.org");
        }
    </script>
</head>
  
<body>
    <button type="button" onclick="loadPage();">
        Load Page
    </button>
</body>
  
</html>  

Output:


Article Tags :