Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 935
Zak Linder Avatar asked Nov 02 '10 15:11

Zak Linder


4 Answers

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);
like image 134
andrewmu Avatar answered Oct 30 '22 07:10

andrewmu


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)....

DetectWakeup.js (must be its own 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);

then in your application, use it like this:

var myWorker = new Worker("DetectWakeup.js");
myWorker.onmessage = function (ev) {
  if (ev && ev.data === 'wakeup') {
     // wakeup here
  }
}
like image 27
Lynn Neir Avatar answered Oct 30 '22 08:10

Lynn Neir


This is a little outdated, but based on the answer by Andrew Mu I've created a simple JQuery plugin to do that: https://github.com/paulokopny/jquery.wakeup-plugin

Usage is simple:

$.wakeUp(function(sleep_time) {
    alert("I have slept for " + sleep_time/1000 + " seconds")
});

Hope this will help someone in the future.

like image 34
Paul Okopny Avatar answered Oct 30 '22 07:10

Paul Okopny


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.

like image 44
brightDot Avatar answered Oct 30 '22 09:10

brightDot