I answered this question awhile ago here: Detect app focus lost & gained in javascript?
I hope it’s still valid