Skip to content

Get redirect URL JavaScript

  • by

To get the redirect URL using JavaScript, you can utilize the XMLHttpRequest object or the newer fetch() API to make an HTTP request and inspect the response headers. Here’s an example using the fetch() API:

fetch('http://example.com', { redirect: 'manual' })
  .then(response => {
    // Get the redirect URL
    var redirectURL = response.headers.get('Location');
    console.log(redirectURL);
  })
  .catch(error => {
    console.error('Error:', error);
  });

Get redirect URL JavaScript example

Simple example code.

<!DOCTYPE html>
<html>
<head>
  <title>Get Redirect URL</title>
  <script>
    function getRedirectURL(url) {
      return fetch(url, { redirect: 'manual' })
        .then(response => {
          if (response.ok) {
            // If the response is not a redirect, return the URL
            return response.url;
          } else {
            // If the response is a redirect, get the Location header
            return response.headers.get('Location');
          }
        });
    }

    function handleButtonClick() {
      var url = document.getElementById('urlInput').value;

      getRedirectURL(url)
        .then(redirectURL => {
          document.getElementById('result').textContent = 'Redirect URL: ' + redirectURL;
        })
        .catch(error => {
          document.getElementById('result').textContent = 'Error: ' + error;
        });
    }
  </script>
</head>
<body>
  <h1>Get Redirect URL</h1>
  <p>Enter a URL to get its redirect URL:</p>
  <input type="text" id="urlInput" placeholder="Enter URL">
  <button onclick="handleButtonClick()">Get Redirect URL</button>
  <p id="result"></p>
</body>
</html>

Output:

Get redirect URL JavaScript

When the button is clicked, the handleButtonClick function is executed. It retrieves the URL entered by the user from the input field, calls the getRedirectURL function with the URL, and updates the resulting paragraph with the obtained redirect URL or any error message.

You can save this HTML code to an HTML file, open it in a web browser, enter a URL, and click the button to see the resulting redirect URL or error message.

Comment if you have any doubts or suggestions on this JS URL topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *