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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With