javascripthtmlhttpfirefox-os

Detect screen on/off with JavaScript


I have a very strange problem here, and that is detecting whether the screen is on/active or not. The platform I'm developing for is KaiOS (Firefox OS), and as many already know, this OS has very resource-limited hardware/device portfolio, hence my 'problem'.

The app I have here requires me to POST to a server (specifically a Kodi JSON-RPC server) every one second, then update a HTML meter and label indicating time elapsed. I use a setTimeout(updateTimeElapsed, 1000) to perform this. This is quite resource intensive (for a feature phone device), involving the WiFi to be activated all the time.

What I'm trying to (very unsuccessfully) achieve is detect whether the screen is on or not, then invoking the updateTimeElapsed function every 1 second (which hopefully ensures once the screen is off, the refresh will stop, and once screen is on, refresh continues). Is there any way to achieve this?


Solution

  • You could use the visibilitychange event and check document.visibilityState.

    Use it like this:

    document.addEventListener('visibilitychange', function() {
      if(document.visibilityState == 'hidden') {
        //enter code for pausing refresh
      }
      else if(document.visibilityState == 'visible') {
        //resume refresh
      }
    });