Can any desktop browsers detect when the computer resumes from sleep?

It would be nice if the computer’s ‘wake up’ event was propagated to the browser and available in the JavaScript API. Does anyone know if anything like this is implemented?

6 thoughts on “Can any desktop browsers detect when the computer resumes from sleep?”

  1. I don’t know of any direct method to do this, but one way you could get a good idea of when it happens is to set up a setInterval task that runs, say every 2 seconds, and stores the time it last ran. Then check to see if the last time it ran is very much older than 2 seconds.

    var lastTime = (new Date()).getTime();
    
    setInterval(function() {
      var currentTime = (new Date()).getTime();
      if (currentTime > (lastTime + 2000*2)) {  // ignore small delays
        // Probably just woke up!
      }
      lastTime = currentTime;
    }, 2000);
    
    Reply
  2. Apart from very good answers and explanations by others, you can also depend on online, offline events. Keeping aside whether online is really online or not, usually, this event ALSO gets triggered when user’s machine is back from sleep apart from having real internet disconnection.

    So, the ideal solution would be having timer check combined with the online and offline events.

    Reply
  3. One of the problems you might encounter with methods above is that alert boxes or other modal type windows will pause JS execution possibly causing a false wake up indication. One way to solve this problem is to use web workers (supported on newer browsers)….

    var myWorker = new Worker("DetectWakeup.js");
    myWorker.onmessage = function (ev) {
      if (ev && ev.data === 'wakeup') {
         // wakeup here
      }
    }
    
    // DetectWakeup.js (put in a separate file)
    var lastTime = (new Date()).getTime();
    var checkInterval = 10000;
    
    setInterval(function () {
        var currentTime = (new Date()).getTime();
    
        if (currentTime > (lastTime + checkInterval * 2)) {  // ignore small delays
            postMessage("wakeup");
        }
    
        lastTime = currentTime;
    }, checkInterval);
    
    Reply
  4. var lastTime = (new Date()).getTime();
    
    setInterval(function() {
      var currentTime = (new Date()).getTime();
      if (currentTime > (lastTime + 2000*2)) {  // ignore small delays
        setTimeout(function() {
         //enter code here, it will run after wake up
        }, 2000);
      }
      lastTime = currentTime;
    }, 2000);
    
    Reply
  5. Another way, session time calculation
    
     setInterval(function(){ 
            let last = parseInt(localStorage.getItem('sessionTime'));
            let now =  (new Date()).getTime();
    
            const diffTime = Math.abs(now - last + 2000 * 2);
            if (diffTime > 480000) {
              _this.authService.logout(1);
            }
           }, 3000);
    
    Reply

Leave a Comment