Prevent redirection of Xmlhttprequest

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.


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.


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.