2

I'm trying to detect the internet connection status with this piece of code

  console.log('here');
  window.addEventListener('offline', function (event) {
    console.log('You lost connection.');
  });
  window.addEventListener('online', function (event) {
    console.log('You are back online.');
  });

I cut off the internet and nothing happens. No log in the console, only the initial here I'm adding this in a basic block in a blank html page, nothing fancy. It seems the events online and offline do not exist on the window object.

UPDATE: this is very weird because I developed this feature on exactly the same environment: the same laptop, OS: windows, browsers chrome and firefox and it was working. Now it does not work. Also I tested using another pc and it works.

rungurean
  • 47
  • 4
  • Does this answer your question? [Detect the Internet connection is offline?](https://stackoverflow.com/questions/189430/detect-the-internet-connection-is-offline) – Anurag Srivastava Mar 09 '20 at 18:10
  • https://developer.mozilla.org/en-US/docs/Web/API/NavigatorOnLine/Online_and_offline_events – Sterling Archer Mar 09 '20 at 18:10
  • It looks like those events are non-standard. See [this](https://developer.mozilla.org/en-US/docs/Web/API/NavigatorOnLine/Online_and_offline_events) for details. – Scott Marcus Mar 09 '20 at 18:11
  • @AnuragSrivastava You're answer did not help. Why did you close my question? Anyway. This helped: https://stackoverflow.com/questions/55375672/the-online-api-isnt-working-in-any-browser?answertab=active#tab-top It was because some network connections added by Virtual Box. – rungurean Mar 10 '20 at 07:28
  • I updated the duplicate link. Thanks @rungurean for finding it. – Kaiido Mar 10 '20 at 07:29

1 Answers1

0

In HTML5 you can use the navigator.onLine property.

Look here: http://www.w3.org/TR/offline-webapps/#related

Probably your current behavior is random as the javascript only ready the "browser" variable and then knows if you're offline and online, but it doesn't actually check the Network Connection.

Adharsh M
  • 2,773
  • 2
  • 20
  • 33