J Dillon
J Dillon

Reputation: 45

Handle web app Javascript notifications better when screen is locked

In my web app I create desktop notifications on some page loads, depending on the state of things, and the page loads every two minutes. It's a simple notification, like this:

// if warning applies:
new Notification("Warning!", {body: "You must take some action"});

meaning that if you have the app open (and the warning applies) then you'll get a pop up every couple of minutes but each will disappear after about 20 seconds (whatever the browser behavior is).

So far, so good. My problem is what happens when the user's PC is locked. If the user comes back to their locked PC after a period where notifications should have popped up, then they will find they all try to pop up in series, meaning they have to either wait a long time for them to clear or close them all -- annoying!

The behavior I would really like is that the notifications should go through their normal lifecycle while the screen is locked, i.e. popup and disappear. Failing that, I would like them to simply not fire if the screen is locked.

Does anyone know how to achieve this?

Upvotes: 2

Views: 273

Answers (1)

terales
terales

Reputation: 3200

See How to detect desktop is locked in javascript and Can JavaScript detect when the PC is locked or the screensaver activates? for discussion about detection idle state.

In short: you can't check if screen is locked on web, but you can in browser extension.


For notifications you can close any previous notifications before showing new:

function spawnNotification(theBody, theIcon, theTitle, prevNotification) {
  var options = {
      body: theBody,
      icon: theIcon
  }

  // Close previous notification before showing new one
  prevNotification.close.call(prevNotification)

  var n = new Notification(theTitle,options);
  setTimeout(n.close.bind(n), 4000);

  return n
}

Upvotes: 1

Related Questions