1

There is a javascript line (you can try it in the browser console)

window.location.href='http://example.com'

that will push you to http://example.com

In the Browser(Google Chrome)-> Developer Tools-> Network section you may see the Status is 200 for it.

The question is:

how to get the status code 200/404/302 right BEFORE executing

window.location.href='http://example.com'

Thank you.

P.S. jQuery is OK for using.

Haradzieniec
  • 9,086
  • 31
  • 117
  • 212
  • 5
    You would have to load it with Ajax first and it has to be same domain or CORs enabled. – epascarello Jul 17 '15 at 16:47
  • @epascarello has the correct answer here, although if you are wanting to do something when it is not available, there should be an error page served from the server for this case. It should not be the JS's job to provide the handling in this specific case. (I am basing this off the specific usage of window.location.href). – Sinistralis Jul 17 '15 at 16:52

2 Answers2

2

The only way to get the status code would be to make the request before you navigate there. That means make an Ajax call to the resource and check the status. Only downside to this is the Same Origin Policy so the sites need to be in the same domain or they have to have CORS enabled for your resource.

epascarello
  • 204,599
  • 20
  • 195
  • 236
1

The HTTP status code are generated by the server, so some HTTP request against the server needs to be executed BEFORE you can get a status code -- so you would need to do an Ajax call on the url -- adapting the simple example in JQuery.get you will have something like;

$.get( "http://example.com", function( data ) {
  // Yeahh the URL works, we can do the page switch
  window.location.href='http://example.com';
});

There are other examples in JQuery.get which deals with error handling etc, but you can read those for yourself.

Of cause, you don't need the entire page to get just the status, you can execute just a HTTP-HEAD which you can see discussed here

With all of this you may run into cross-site scripting restrictions which you can go an research separately -- there are lot of stack-overflow questions on that already.

Community
  • 1
  • 1
Soren
  • 14,402
  • 4
  • 41
  • 67