Open In App

How to redirect to a relative URL in JavaScript?

Improve
Improve
Like Article
Like
Save
Share
Report

To redirect to a relative URL in JavaScript, you could use window.location.href. It is a property in JavaScript that represents the complete URL of the current page. It can be used to get the current URL or to navigate to a new URL by assigning a new URL to it.

Approach

  1. HTML Structure:
    • The HTML file includes a simple button with the text “Redirect.” When the button is clicked, it triggers the redirectToRelativeURL function.
  2. JavaScript Function (redirectToRelativeURL):
    • The redirectToRelativeURL function is defined in the <script> tag.
    • It begins by specifying the relative URL ('geeksforgeeks.org') to which the page should redirect.
  3. Construct Absolute URL:
    • The function uses the URL object to construct an absolute URL based on the current location (window.location.href) and the specified relative URL.
    • The URL object takes care of handling relative paths and ensures the resulting URL is valid.
  4. Redirect:
    • Finally, the function sets window.location.href to the constructed absolute URL, causing the browser to navigate to the specified location.

Example: Below is the implementation.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible"
          content="IE=edge">
    <meta name="viewport" content=
"width=device-width, initial-scale=1.0">
    <title>Redirect Example</title>
</head>
 
<body>
    <h2>Redirect Example</h2>
    <button onclick="redirectToRelativeURL()">Redirect</button>
 
    <script>
        // Function to redirect to a relative URL
        function redirectToRelativeURL() {
            // Relative URL to redirect to
            const relativeURL =
            // Construct absolute URL based
            // on the current location
            const absoluteURL =
            new URL(relativeURL, window.location.href);
 
            // Log the absolute URL (optional)
            console.log('Redirecting to:', absoluteURL.href);
 
            // Redirect to the absolute URL
            window.location.href = absoluteURL.href;
        }
    </script>
</body>
 
</html>


Output:

gfg



Last Updated : 30 Jan, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads