I was tracking down some ridiculously high load times that my app's javascript reported, and found that Android (and iOS) pause some JavaScript execution when the window is in the background or the display is off.
On Android, I found that I could use the window.onfocus
and onblur
events to detect when the app was switching to the background (and js execution would soon be paused, at least for new scripts), but I can't find a way to detect when the screen is turned on or off. Is this possible?
(On Safari, I had similar results except that onfocus
and onblur
didn't fire reliably.)
There is few options to check it:
Using Visibility API
Using
focus
andblur
events to detect browser tab visibility:I just found a pretty good solution for my use case:
When the screen is turned off (or JS is paused for any reason), the next interval is delayed until JS execution resumes. In my code, I can just adjust the timers by the
offBy
amount and call it good.In quick testing, this seemed to work well on both Android 4.2.2's browser and Safari on iOS 6.1.3.
what will you do in your script once you now that the screen turns off? Well anyway, you can inject Java objects ( http://developer.android.com/reference/android/webkit/WebView.html#addJavascriptInterface(java.lang.Object,%20java.lang.String) ) to interface with the activity and proxy all information you require in JS world.
Found a nice function here:
http://rakaz.nl/2009/09/iphone-webapps-101-detecting-essential-information-about-your-iphone.html
To register for event:
This is consistent with Cordova which also fires the
resume
event.