Reputation: 1
I'd like to get the redirect url from a site via XMLHttpRequest
Here's the code below
let url = 'https://some-site.com/Z/12345/54321'
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(response) {
var xhr2 = response.target;
console.log(xhr.location)
if (xhr.readyState === 4 && xhr.status === 302) {
var redirectURL = xhr.location;
}
}
xhr.onerror = (response) => {
debugger
}
xhr.open('GET', url, true);
xhr.send();
so the problem is, the website, as the code below
let url = 'https://some-site.com/Z/12345/54321'
is only redirecting to another website
I only want to get the redirect url
I don't know how the 'https://some-site.com/Z/12345/54321'
coded
so the TLDR is send request to 'https://some-site.com/Z/12345/54321'
=> from 'https://some-site.com/Z/12345/54321'
redirected to the url that I want to get
Is there any way to get the url?
Upvotes: 0
Views: 394
Reputation: 10627
You should use XMLHttpRequestInstance.responseURL:
const xhr = new XMLHttpRequest;
xhr.open('GET', 'https://some-site.com/Z/12345/54321'); xhr.responseType = 'json'
xhr.onload = function(){ /* no need to use onreadystatechange in xhr2 */
// this.response is JSON response
// this.responseURL is what you want
}
xhr.onerror = function(e){
// e is ErrorEvent Obj
}
xhr.send();
Upvotes: 1