My JavaScript code stop running when the mobile screen is locked?

Here is my code:

firebase.initializeApp(config);
if(!window.Notification){
  alert('Not supported');
}else{
  Notification.requestPermission().then(function(p){
    if(p=='denied'){
      alert('You denied to show notification');
    }else if(p=='granted'){
      alert('You allowed to show notification');
    }
  });
}
var database = firebase.database().ref("sensor/Motion");
database.on('child_added', function() {

  $("#Mt").val("Motion detected");
  $("#dateM").val( moment().format('LLL') );
  if(Notification.permission!=='default'){
    var notification = new Notification('Alert', {
      icon: 'alert-icon-red.png',
      body: "Motion detected!",
    });

  }else{
    alert('Please allow the notification first');
  }

Everything works fine in my desktop browser but on my Android device, when the screen is locked, it works for a few minute and after that it doesn't work. I get no notifications.

Upvotes: 1

Views: 458

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599131

It sounds like your mobile browser is stopping tasks when the screen is locked, likely to improve battery life. That in general sounds like a good thing.

If you want to alert the user of an event that happens when they're not using their device, consider using Firebase Cloud Messaging for sending and handling those messages. This ensures it uses a communication channel that is more likely to be active when the user is not actively using the app.

Upvotes: 2

Related Questions