burtek
burtek

Reputation: 2685

detecting a redirect with javascript - how?

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.

Upvotes: 24

Views: 49700

Answers (2)

stack
stack

Reputation: 9

Here is simple solution for your question.

x.addEventListener('readystatechange',function(){

    const url = 'https://your/request/url';
    if(this.responseURL != url){
        alert('redirected');
    }

});

Upvotes: -2

saml
saml

Reputation: 6802

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.

Upvotes: 10

Related Questions