1

So I jumped on the train of service workers and push notifications. It seems to work well however I cannot figure out how to suppress notifications being displayed by the browser when the user is active in the tab, i.e. the tab is focused. Displaying notifications even while the user is working with the app would be bothering them too much -> they would just close them -> could lead to messages not being delivered if this exceeds some threshold.

This document mentions to add config to ngsw-config.json, so I did put there:

"push": {
  "showNotifications": true,
  "backgroundOnly": true
}

However no matter what, messages are always displayed.

Should I just simply subscribe to messages, send them as data instead of notification and display them manually?

constructor(swPush: SwPush) {
  if (swPush.isEnabled) {
    swPush.messages.subscribe(message => {
      //display the message if tab is not active
    });
  }
}

If I do this, will that work in the background on mobile?

Edit: This approach of deciding in code whether to display message or not does work in Firefox but in Chrome I get 'The site has been updated in the background' message.

Frankly, I don't know how to move forward as I quite don't know what to do in SwPush.messages Observable to make Chrome happy. :(

PeS
  • 3,757
  • 3
  • 40
  • 51
  • Have you take a look at https://www.npmjs.com/package/activity-detector? – Maxime Gélinas Aug 01 '18 at 00:44
  • @MaximeGélinas No but that is not the problem. It is not a matter of whether user is idle or not, the problem is that I do want messages to be displayed when the app runs in the background (browser started on PC, anytime on mobile[?]) but not when the app is open, visible in active tab or launched as PWA. – PeS Aug 01 '18 at 01:00
  • I have changed the title to be maybe less confusing. – PeS Aug 01 '18 at 01:10

1 Answers1

1

I know it's been a while this was asked but in case it helps someone else.

How about handling it manually. Implement Focus and Blur events. You can also include "beforeunload" event listener to capture situation where the app went from Focus to Closed.

If you use the above events to capture a isActive state and then ensure that notifications are only sent when the isActive is false.

  @HostListener('window:focus')
  onFocus() {
    isActive = true;
  }

@HostListener('window:blur')
  onBlur() {
    isActive = false;
  }

  // Before window is closed
  @HostListener('window:beforeunload')
  beforeunloadHandler() {
    isActive = false;
  }
Tobi Teps
  • 160
  • 1
  • 4