5

How can I retrieve the http status code returned from the server (200, 302 etc.) from javascript/jquery?

I am NOT looking to get this from an ajax request. I want to retrieve it on the initial page load and take some custom actions based on the status code.

P.S, The solution doesn't necessarily need to be cross browser. This is for an internal application and so any browser specific solutions would be acceptable.

reggaemahn
  • 6,272
  • 6
  • 34
  • 59

1 Answers1

6

Just to confirm what's been said in the comments:

  1. It's not possible to do this reliably from the server. The response might not come from the original server, e.g. if there's a cache in between the server and client.

  2. It's not possible to do this reliably using AJAX to re-request the same page. The response to the second request might differ from that of the original request, e.g. if the server returns a not-modified response to the second request.

  3. It's not possible to do this with standard browsers using any known JavaScript API. That's a question that's been asked often. See, for example Accessing the web page's HTTP Headers in JavaScript

Community
  • 1
  • 1
Stephen Thomas
  • 13,843
  • 2
  • 32
  • 53
  • There is a way to do this reliably with a webworker. But it assumes you've loaded the page at least once before so that you installed the webworker, after that you can intercept all the requests and their status code, the only annoying part is that it doesn't work for the first page load but you could ask it to reload the page straight away after install to mitigate this issue – Tofandel Feb 01 '22 at 21:40