132

Is it possible to prevent the browser from following redirects when sending XMLHttpRequest-s (i.e. to get the redirect status code back and handle it myself)?

6 Answers 6

111

Not according to the W3C standard for the XMLHttpRequest object (emphasis added):

If the response is an HTTP redirect:

If the origin of the URL conveyed by the Location header is same origin with the XMLHttpRequest origin and the redirect does not violate infinite loop precautions, transparently follow the redirect while observing the same-origin request event rules.

They were considering it for a future release:

This specification does not include the following features which are being considered for a future version of this specification:

  • Property to disable following redirects;

but the latest specification no longer mentions this.

4
  • 11
    What is ridiculous is when the transparent redirect involves overwriting some HTTP headers that were set in the original request. Specifically, if the "Accept" header was set to a specific content-type, Firefox fails to include this header when following the redirect (which makes it a tad more difficult to develop fully REST-based web services that use this header... grumble).
    – david
    May 26, 2011 at 8:47
  • 1
    Some more searching brought me this rather old bug report: bugzilla.mozilla.org/show_bug.cgi?id=401564
    – david
    May 26, 2011 at 9:22
  • 2
    Agree, totally rediculus design flaw.
    – Rasive
    Dec 12, 2014 at 10:56
  • It is now possible by using Fetch API. So this answer is no longer valid.
    – Nux
    May 25, 2022 at 16:19
38

The new Fetch API supports different modes of redirect handling: follow, error, and manual, but I can't find a way to view the new URL or the status code when the redirection has been canceled. You just can stop the redirection itself, and then it looks like an error (empty response). If that's all you need, you are good to go. Also you should be aware that the requests made via this API are not cancelable yet. They are now.

As for XMLHttpRequest, you can HEAD the server and inspect whether the URL has changed:

var http = new XMLHttpRequest();
http.open('HEAD', '/the/url');
http.onreadystatechange = function() {
    if (this.readyState === this.DONE) {
        console.log(this.responseURL);
    }
};
http.send();

You won't get the status code, but will find the new URL without downloading the whole page from it.

2
  • Sometimes using OPTIONS may be a better choice, anyway only works for non general purpose, etc. administrator had configured redirect the whole site / schema, such as HTTP -> HTTPS Dec 21, 2016 at 6:05
  • You cannot find a way because there is no way to find out what the destination URL is. This is for security reasons. See: fetch.spec.whatwg.org/#atomic-http-redirect-handling
    – Nux
    May 25, 2022 at 16:17
12

No you there isn't any place in the API exposed by XMLHttpRequest that allows you to override its default behaviour of following a 301 or 302 automatically.

If the client is running IE on windows then you can use WinHTTP instead to set an option to prevent that behaviour but thats a very limiting solution.

0
11

You can use responseURL property to get the redirect destination or check whether the response was ultimately fetched from a location you accept.
This of course means the result is fetched anyway, but at least you can get the necessary info about the redirect destination and for example detect conditions when you would like to discard the response.

1
3

I extended user's answer to include an abort() call. It seems like this prevents the server from sending too much data when all you want is the redirect url.

var url = 'the url'
var http = new XMLHttpRequest();
http.open('GET', url);
http.onreadystatechange = function() {
    if (this.readyState === this.DONE) {
        console.log(this.responseURL)
        this.abort() // This seems to stop the response
    }
}
http.send()

In real life I wrapped the above code in a promise, but it made the code hard to read.

Also, I don't understand why getting the redirect url needs to be this difficult, but that is a question for another time and place.

1
  • I tried jquery, fetch, and finally XHR, only xhr worked and your code works for POST request as well. Awesome!
    – cyper
    Jul 26 at 5:08
0

It is not possible to handle redirect or 302 status at client side as answered in other comments. However you can prevent redirection. To do that you can set request header "X-Requested-With" with "XMLHttpRequest" xhttp.setRequestHeader("X-Requested-With", "XMLHttpRequest"); This should be done after open but before send. Example below

let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
   if (this.readyState == 4 && this.status == 200) {
         reqObj.success(JSON.parse(this.responseText))
   } else if (this.status != 200) {
         reqObj.error(this.statusText)
   }
};
xhttp.open(reqObj.type, reqObj.url, reqObj.async);
xhttp.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhttp.send();
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.