72

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?

Zak Linder
  • 1,016
  • 1
  • 9
  • 13
  • I doubt it since it would probably have to bridge the gap between isolated browser and operating system, but I'll be interested to find out of it is, in fact, possible. – Joel Etherton Nov 02 '10 at 15:22
  • Define "sleep", as this term varies widely per-device. – Nick Craver Nov 02 '10 at 15:24
  • I've edited the question to be specifically about desktop browsers. I'd this question to be a bit device-agnostic since webapps that would use such an API would presumably target multiple platforms/devices. – Zak Linder Nov 04 '10 at 04:38
  • 1
    @Nick in my specific use-case the webapp initiates a constant connection with the server. If the device goes to sleep this connection is severed and should be re-initiated on wake-up. There doesn't seem to be a good way of doing this automatically (I dont want to force the user to press a button :P). – Zak Linder Nov 04 '10 at 04:41

6 Answers6

77

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);
andrewmu
  • 14,276
  • 4
  • 39
  • 37
  • 7
    This is similar to how I would go about it -- only, use a much larger interval than two seconds :-) I imagine 5minutes would be a reasonably small value (it is rare that my computer sleeps for any small amount of time). Also, another way is to record how many "ticks" occurred vs. how many were supposed to occur (keep it on an average). There is also the edge-case of a time change (DST -- so best to use UTC -- or user) that may be marginalized. –  Nov 04 '10 at 04:46
  • It is good, but when you fire an ajax request after the sleep, it fails! Why? Having alert statement before calling the ajax request would work out! Why? – moderns May 18 '14 at 19:54
  • @moderns this is because the network connection probably isn't fully up yet, but the alert stalls the script until a user clicks on it, which is plenty of time for things to get running. – nightpool Jul 29 '14 at 00:44
  • 6
    A fine idea, but remember that [`setInterval` and `setTimeout` execution speed can be affected when the tab is in the background](http://stackoverflow.com/questions/6032429/chrome-timeouts-interval-suspended-in-background-tabs), and that's by design. – a paid nerd Aug 26 '14 at 01:20
31

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
  }
}
MalcolmOcean
  • 2,807
  • 2
  • 29
  • 38
Lynn Neir
  • 321
  • 3
  • 6
  • Could you please give a demo? I have tried working it out, but it doesn't give anything. Not even in the console. –  Sep 21 '16 at 15:20
5

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.

Matthew
  • 1,630
  • 1
  • 14
  • 19
Paul Okopny
  • 51
  • 1
  • 2
3

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.

brightDot
  • 329
  • 2
  • 11
  • 2
    Interesting suggestion... I so wanted this to work, but it does not for me (Firefox 71 or Safari 13 on macOS, or Chrome 78 on Windows). In what context does this work? – Hugues M. Dec 06 '19 at 14:40
  • 1
    This would not work in detecting if computer went to sleep or waking up, it specifically looks for internet connection turning off or on – Einar Ólafsson Jun 02 '21 at 21:46
  • But definitely it is working as intended. Check out the documentation: https://developer.mozilla.org/en-US/docs/Web/API/Document/ononline – Hubo Nov 18 '21 at 22:13
  • The online and offline event fire for me when coming out of sleep in FF but not Edge – user1689571 Feb 06 '23 at 17:51
0
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);
  • setInterval function running when system sleeping, setTimeout function also running when system sleeping, but code run when system wake up(event loop) – Serhii Lyzun Oct 23 '18 at 11:01
0

Another way, using the session time

 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);
Peter Meadley
  • 509
  • 2
  • 16
Behram Bazo
  • 230
  • 2
  • 6