Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

detecting a redirect with javascript - how?

Tags:

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.

like image 283
burtek Avatar asked Mar 09 '12 17:03

burtek


People also ask

How do I capture a URL redirect?

Type "cache:sitename.com" in the address bar of Chrome and press "Enter" where "sitename" is the URL that is generating the redirect. This will show you a cached version of the site on which you can use the Inspect Element pane to find and capture the redirect URL.


1 Answers

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.

like image 149
saml Avatar answered Sep 17 '22 02:09

saml