6

I am trying to write an extension that will cache page content for offline reading. If the user activates the extension's popup while offline, I would like to show the cached content. Currently, I am thinking I can make an ajax request and wait to see if it fails, but if there is a part of the chrome API that would let me do this more quickly, that would be ideal.

I have done some googling and haven't come across anything.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Chris Sobolewski
  • 12,819
  • 12
  • 63
  • 96

4 Answers4

19
if (navigator.onLine) {
  // Online
} else {
  // Offline
}

It also supports event listeners.

https://developer.mozilla.org/en/Online_and_offline_events

abraham
  • 46,583
  • 10
  • 100
  • 152
  • 2
    navigator.onLine is not correctly reflect the change immediately if network status change – Atif Hussain Oct 19 '16 at 05:44
  • 1
    navigator.onLine is very unreliable. See https://stackoverflow.com/questions/14283124/navigator-online-not-always-working – Chiwda Oct 25 '17 at 06:35
3

navigator.onLine reports correctly in most instances, but one I found where it is incorrect is if you were to disable WiFi, but you have a PoE ethernet cable plugged into your NIC port. Even though the phone may be offline, navigator.onLine reports that the browser is actually online.

Sage
  • 4,769
  • 1
  • 21
  • 28
3

Sounds like navigator.Online checks for a network connection, not necessarily an internet connection. If you want to confirm the user has access to the internet, I think you can use this option in conjunction with a periodic or on demand Ajax request to google or some other reliable site and monitor the response to determine if the user has a stable internet connection.

Rob Lester
  • 83
  • 6
3

Tried navigator.onLine ? I read it's unreliable but I just did a test (disconnecting from WiFi) and it worked.

Jim Blackler
  • 22,946
  • 12
  • 85
  • 101