Is there any way to detect whether a webpage is going to redirect me to another, knowing its URL? I mean the situation when you type URL in a text field and the script examines it for 3xx redirections.
Asked
Active
Viewed 4.3k times
24
-
There is an event `onbeforeunload`, is that what you want? – fardjad Mar 09 '12 at 17:45
-
@fardjad Maybe I didn't explain it correctly. I need something like [this](http://www.internetofficer.com/seo-tool/redirect-check/), but with javascript, not php – burtek Mar 09 '12 at 17:56
-
If it meets the same origin policy you should probably be able to get the 302 header via the XHR object. – zzzzBov Mar 09 '12 at 18:04
-
Maybe you could use a iframe... Load that url in a iframe and compare its location. Although you might need to work around the cross-domain issue. – MorrisLiang Mar 09 '12 at 18:05
2 Answers
10
Yes, you can do this quite easily in Javascript. It'd look something like:
var xhr = new XMLHttpRequest();
xhr.onload = function() {
if (this.status < 400 && this.status >= 300) {
alert('this redirects to ' + this.getResponseHeader("Location"));
} else {
alert('doesn\'t redirect ');
}
}
xhr.open('HEAD', '/my/location', true);
xhr.send();
Unfortunately, this only works on your own server, unless you hit a server with CORS set up. If you wanted to work uniformly across any domain, you're going to have to do it server-side.

saml
- 6,702
- 1
- 34
- 30
-
2I might be wrong here but I think this might not work and the only method to check that you were redirected or not is to inspect **responseURL** attribute https://xhr.spec.whatwg.org/#the-responseurl-attribute If it is different then the URL used in **open** method there was a redirect – szydan Aug 23 '19 at 19:50
0
Here is simple solution for your question.
x.addEventListener('readystatechange',function(){
const url = 'https://your/request/url';
if(this.responseURL != url){
alert('redirected');
}
});

stack
- 1
- 4