Languages
[Edit]
EN

JavaScript - detect URL request redirection

9 points
Created by:
Sujay
512

In this short article, we would like to show how to detect URL request redirection using JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

const url = 'https://dirask.com/posts/1yR6lD';

fetch(url)
    .then(response => {
        const redirectionUrl = (response.redirected ? response.url : null);
        console.log('Redirection URL: ' + redirectionUrl);
    })
    .catch(error => console.error(error));

 

Reusable logic

XHR based solution

This solution works in older web browsers.

// ONLINE-RUNNER:browser;

function detectRedirection(url, callback) {
  	var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            var redirectionUrl = xhr.responseURL;
          	callback(url === redirectionUrl ? null : redirectionUrl);
        }
    };
    xhr.open('GET', url, true);
    xhr.send(null);
}


// Usage example:

detectRedirection('https://dirask.com/posts/1yR6lD', function(redirectionUrl) {
    console.log('Redirection URL: ' + redirectionUrl);
});

 

fetch() based solution

Warning: Fetch API was introduced in major web browser around 2015-2017 (ES6), in Node.js in 2022, and in Deno in 2020. 

// ONLINE-RUNNER:browser;

const detectRedirection = async (url) => {
    const response = await fetch(url);
    return response.redirected ? response.url : null;
};


// Usage example:

(async () => {
    try {
        const redirectionUrl = await detectRedirection('https://dirask.com/posts/1yR6lD');
        console.log('Redirection URL: ' + redirectionUrl);
    } catch (error) {
        console.error(error);
    }
})();

 

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join