This idea is bouncing around in my brain, and I was wondering what other Moodle devs thought of it:
The idea would be to get the core/ajax AMD module to check what happens when we make an AJAX call back to Moodle, so that we can know if Moodle seems to have gone down.
I think all we need to do is, around https://github.com/moodle/moodle/blob/master/lib/amd/src/ajax.js#L102 check if textStatus = "timeout", and if it is, set a field this.connectionStatus = OFFLINE. Also, any time an Ajax call works, we can set this.connectionStatus = ONLINE. We might also want to track the time when this happened.
Then there could be an API like ajax.getLastKnownConnectionStatus, and we could fire a custom event any time the status changes. That would give other code ways to use the information we now have. E.g. we could stop users form submitting a form and losing their data if we are pretty sure that the submit will fail.
I think that would be enough for an initial implementation, but in time we might be able to detect other situations, for example if the user has got logged out (which you should be able to detect because the sesskey stops working which is a specific error).
What do people think? Would it be worth me making a tracker issue for this.