4

I want to put condition for login page that if an internet connection is available, then check the server database, otherwise check the localstorage.

I have tried to check this via an AJAX call, but when the page is loaded from the appcache, it always shows me that I'm connected to the Internet. I know a little about fallback section in the manifest file, but I don't know how to use it in my case.

What should I do to handle events when offline?

MC Emperor
  • 22,334
  • 15
  • 80
  • 130
Bharat
  • 93
  • 11
  • Define "available". This is not necessarily easy. Sometimes it's just plain broken, but the problem is when it's technically working, but unusably slow. – tadman Apr 25 '17 at 06:37
  • `but when the page is loaded from the appcache, it always shows me that I'm connected to the Internet` your ajax response is cached. – gurvinder372 Apr 25 '17 at 08:48

1 Answers1

7

You could easily pull the client's internet status by using Navigator.onLine which returns a boolean.

if (!navigator.onLine) {
   //Browser is offline, pull data from localStorage
} else {
   //Browser is online, pull data through AJAX
}

You could also bind it to an event listener, so that you can change the data source on the fly:

window.addEventListener('offline', function(e) { 
   //Browser is offline, pull data from localStorage
});

Reference: https://developer.mozilla.org/en-US/docs/Web/API/NavigatorOnLine/onLine

At the time of posting, this function is supported on IE11, IE Edge, Firefox 51+ Chrome 49+, Safari 10+, iOS 9.3+, Android Browser 4.4+ and Chrome for Android 57+


Update It appears that I misunderstood your original question. After checking your manifest file. The code to pull the data from localStorage should go into the FALLBACK section. You should place your localStorage function into the offline.html file.

FALLBACK:
/ offline.html

Reference: https://developer.mozilla.org/en-US/docs/Web/HTML/Using_the_application_cache

James Wong
  • 4,529
  • 4
  • 48
  • 65
  • @Bharat Show us how you implemented it, paste your code into jsfiddle and paste the link here :) the function above works, we are using it in many HTML webapps. Am sure it's just some implementation quirks. Let us take a look. – James Wong Apr 25 '17 at 08:53
  • Sure. https://jsfiddle.net/bharats/61bxtvhy/15/ I have put Manifest in HTML section. Thanks – Bharat Apr 25 '17 at 11:37
  • I've updated my answer. The browser when it detects the user is offline, will call the files from the section declared in `FALLBACK`. That is where you should place your code. – James Wong Apr 25 '17 at 11:51
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/142681/discussion-between-bharat-and-james-wong). – Bharat Apr 26 '17 at 04:44