HTML Location port Property: Getting and Setting the Port Number

The HTML Location port property is a crucial part of the Document Object Model (DOM), providing access to the port number of the current URL. It allows you to retrieve or modify the port number, enabling dynamic manipulation of the URL in web applications. This comprehensive guide will explore how to effectively use the Location port property with JavaScript.

What is the Location port Property?

The Location port property returns a string representing the port number of the current URL. If the URL does not explicitly specify a port number, it returns an empty string (""). This property is part of the Location object, which provides information about the current document’s URL.

Syntax

Getting the port number:

let portNumber = location.port;

Setting the port number:

location.port = "8080";

Note: Setting the port property will cause the browser to navigate to the new URL. ⚓

Property Values

| Value | Description |
| :——- | :——————————————————————————————————————— |
| string | The port number as a string. Returns an empty string ("") if no port is specified in the URL. |
| | When setting, the browser navigates to the new URL with the specified port. |
| | If the port is invalid, some browsers might refuse the change or normalize the URL, depending on the browser security. |

Examples of Using the Location port Property

Let’s explore some examples of how to use the Location port property in JavaScript.

Example 1: Getting the Port Number

This example demonstrates how to retrieve the port number from the current URL.

<!DOCTYPE html>
<html>
<head>
    <title>Get Port Number</title>
</head>
<body>
    <p id="getPortResult">The port number is: </p>

    <script>
        const getPortResultElem = document.getElementById("getPortResult");
        const currentPort = location.port;
        getPortResultElem.textContent = "The port number is: " + (currentPort || "default port");
    </script>
</body>
</html>

Output:

If the URL is http://example.com:8080/, the output will be:

The port number is: 8080

If the URL is http://example.com/, the output will be:

The port number is: default port

Example 2: Setting the Port Number

This example demonstrates how to set the port number, causing the browser to navigate to the new URL.

<!DOCTYPE html>
<html>
<head>
    <title>Set Port Number</title>
</head>
<body>
    <button id="setPortButton">Set Port to 3000</button>

    <script>
        const setPortButtonElem = document.getElementById("setPortButton");
        setPortButtonElem.addEventListener("click", function() {
            location.port = "3000";
        });
    </script>
</body>
</html>

When the button is clicked, the browser will navigate to the same URL but with port 3000. For example, if the current URL is http://example.com/, clicking the button will navigate to http://example.com:3000/.

Example 3: Handling Default Ports

This example checks if the port is explicitly specified in the URL. If not, it indicates that the default port is being used (80 for HTTP, 443 for HTTPS).

<!DOCTYPE html>
<html>
<head>
    <title>Check Default Port</title>
</head>
<body>
    <p id="checkPortResult">Port status: </p>

    <script>
        const checkPortResultElem = document.getElementById("checkPortResult");
        const currentPortCheck = location.port;

        if (currentPortCheck === "") {
            const protocol = location.protocol;
            const defaultPort = (protocol === "https:") ? "443" : "80";
            checkPortResultElem.textContent = "Port status: Using default port " + defaultPort + " for " + protocol.slice(0, -1);
        } else {
            checkPortResultElem.textContent = "Port status: Using explicit port " + currentPortCheck;
        }
    </script>
</body>
</html>

Output:

If the URL is http://example.com/, the output will be:

Port status: Using default port 80 for http

If the URL is https://example.com/, the output will be:

Port status: Using default port 443 for https

If the URL is http://example.com:8080/, the output will be:

Port status: Using explicit port 8080

Example 4: Validating and Setting a New Port

This example validates the port number before setting it to ensure it is a valid number.

<!DOCTYPE html>
<html>
<head>
    <title>Validate and Set Port</title>
</head>
<body>
    <input type="number" id="newPortInput" placeholder="Enter new port number">
    <button id="validateSetPortButton">Set New Port</button>
    <p id="validateSetPortResult"></p>

    <script>
        const newPortInputElem = document.getElementById("newPortInput");
        const validateSetPortButtonElem = document.getElementById("validateSetPortButton");
        const validateSetPortResultElem = document.getElementById("validateSetPortResult");

        validateSetPortButtonElem.addEventListener("click", function() {
            const newPort = newPortInputElem.value;

            if (!isNaN(newPort) && newPort >= 1 && newPort <= 65535) {
                location.port = newPort;
            } else {
                validateSetPortResultElem.textContent = "Invalid port number. Please enter a number between 1 and 65535.";
            }
        });
    </script>
</body>
</html>

This code checks if the entered value is a number between 1 and 65535 before attempting to set the port.

Practical Considerations

  • Security: Modifying the location.port can be a security risk if not handled carefully. Always validate and sanitize user inputs.
  • User Experience: Navigating to a new URL can disrupt the user experience. Use this property judiciously.
  • Default Ports: Remember that HTTP defaults to port 80 and HTTPS defaults to port 443. When no port is specified in the URL, the browser uses these defaults.

Browser Support

The location.port property is supported by all major browsers:

  • Chrome
  • Edge
  • Firefox
  • Safari
  • Opera

Conclusion

The HTML Location port property is a useful tool for retrieving and setting the port number of the current URL. By understanding how to use this property, you can create more dynamic and interactive web applications. Remember to handle modifications carefully to ensure a smooth and secure user experience. 🌐