Detecting Location Redirects from JavaScript
2 min read
2 min read
A common scenario for using the HTTP Location response header is during an authentication process where some kind of filter redirects to a login page in case when the user is not or no more authenticated. Handling such redirects from JavaScript turned out to be not so simple as it might initially seem. Stackoverflow has already a post on that and here (or on SO) is how I solved it in the end.
$(document).ajaxComplete(function(e, xhr, settings){But unfortunately the browser handles location redirects completely himself, wherefore the
if(xhr.status === 302){
//check for location header and redirect...
}
});
ajaxComplete
callback won't fire with the 302
status code, but instead it will fire on the location redirect target (when that redirect already happened successfully). As a result, the approach before obviously won't work.LoginPage: http://www.mydomain.com/Loginwhere the url is the one of the invoked Login page due to the location redirect. On the client side you can now check for the presence of the header like
if(xhr.status === 200){You might wonder why I included the url directly in the header value. The problem is that you have no way of detecting the URL of the redirected request in the
var loginPageHeader = xhr.getResponseHeader("LoginPage");
if(loginPageHeader && loginPageHeader !== ""){
window.location.replace(loginPageHeader);
}
}
ajaxComplete
callback. You just get the initial one you started, that is, when you execute a GET /person/1
and you're no more logged in (because the session expired) and the server sends you a 302 redirect
to /login
, then you'll see the /person/1
as the url in your ajaxComplete
callback although the content of the response is the one of your login page. That's why I directly included the url in my custom header.