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:
xxxxxxxxxx
1
const url = 'https://dirask.com/posts/1yR6lD';
2
3
fetch(url)
4
.then(response => {
5
const redirectionUrl = (response.redirected ? response.url : null);
6
console.log('Redirection URL: ' + redirectionUrl);
7
})
8
.catch(error => console.error(error));
This solution works in older web browsers.
xxxxxxxxxx
1
function detectRedirection(url, callback) {
2
var xhr = new XMLHttpRequest();
3
xhr.onreadystatechange = function () {
4
if (xhr.readyState === XMLHttpRequest.DONE) {
5
var redirectionUrl = xhr.responseURL;
6
callback(url === redirectionUrl ? null : redirectionUrl);
7
}
8
};
9
xhr.open('GET', url, true);
10
xhr.send(null);
11
}
12
13
14
// Usage example:
15
16
detectRedirection('https://dirask.com/posts/1yR6lD', function(redirectionUrl) {
17
console.log('Redirection URL: ' + redirectionUrl);
18
});
Warning: Fetch API was introduced in major web browser around 2015-2017 (ES6), in Node.js in 2022, and in Deno in 2020.
xxxxxxxxxx
1
const detectRedirection = async (url) => {
2
const response = await fetch(url);
3
return response.redirected ? response.url : null;
4
};
5
6
7
// Usage example:
8
9
(async () => {
10
try {
11
const redirectionUrl = await detectRedirection('https://dirask.com/posts/1yR6lD');
12
console.log('Redirection URL: ' + redirectionUrl);
13
} catch (error) {
14
console.error(error);
15
}
16
})();