I have an html5 application. It sends stuff to a database. Originally I was doing the database update instantly, however, now I am allowing for offline usage, and instead letting the user choose when to send to the database. (Eg if they are on a plane, they might want to do it later.)
So, now the problem is, if they shutdown, I want to warn them before they do, if they have failed to send any unsent data and allow them to return to send it if necessary. I will ultimately be using local storage until it is sent, so it wont be lost, but the important thing is to let the user know it is as yet unsent.
I will have a global g_bUnsentData = true; if there is unsent data.
Can this be done in javascript, and how can you do it?
Also, as an aside, how do I test for online status, so I can warn the user if they are offline and trying to send data?
See @SmartK8's comment.
Nonetheless, if you bind a function to the beforeunload
event that returns a string, most browsers will display that string and a confirmation to leave the page. For example:
Some browsers might not display your returned string in the confirmation at all. Other browsers, especially mobile ones, will not even prevent the page from being navigated away from.
For testing the online status, navigator.onLine
is a boolean value indicating network availability. It's not available everywhere (Opera, Firefox), but it's a start. See this page at html5 rocks for more details.