EN
JavaScript - detect URL request redirection
9
points
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);
}
})();