Trevor
Trevor

Reputation: 2932

Cordova, how to detect offline accurately

I am looking for a way to detect

  1. Phone is offline, no data or wifi

  2. Phone is online, but is behind a router that blocks access without sign in (like hotels, free wifi hotspots, etc.)

  3. Phone is online, but the server is offline

Number 1 is easy using cordova-network-information Number 2 and 3 are more difficult. I can send an ajax to our server as a heartbeat to test it, but that can't tell the difference between situation 2 and 3.

What's a way I could test for situation 2 and 3 accurately?

My first thought was to ajax something on google to check situation 2, and if 2 passes, then check 3. Does that sound like a good idea?

Thanks

Upvotes: 1

Views: 138

Answers (1)

Aleks G
Aleks G

Reputation: 57326

The way I approached this before is to send an AJAX to my server, as you suggested - to an endpoint that would return a known response. Then in your app test this response.

You are behind a captive portal if one of the following happens:

  • the response is a success (i.e. 2xx code), but doesn't match what you expected
  • you get an ssl certificate mismatch error
  • you get an unexpected 404, 301 or 302 response

If you get a connection error, then most likely your server is down.

Finally, if you get a DNS resolution error, then it most likely an issue with the connection other than the two above (e.g. the network you are connected to simply doesn't have an outside internet connectivity), but possibly your DNS server has gone down.

Of course, all this assumes that you have some connection (i.e. not point 1 in your question). Finally, make sure that you gracefully handle any other exceptions.

Upvotes: 1

Related Questions