Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If (Internet == unavailable) in HTML5 app manifest offiline app

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?

like image 823
Bharat Avatar asked Mar 09 '23 06:03

Bharat


1 Answers

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

like image 118
James Wong Avatar answered Mar 11 '23 20:03

James Wong