OneSignal / OneSignal-Website-SDK

OneSignal is a push notification service for web and mobile apps. This SDK makes it easy to integrate your website with OneSignal Push Notifications. https://onesignal.com
Other
383 stars 115 forks source link

[Question]: How to prevent web notifications from showing when tab is being viewed #1164

Open thatop007 opened 3 months ago

thatop007 commented 3 months ago

How can we help?

We currently able to receive web desktop notifications successfully and would like to know if it is possible and how to prevent web notifications from showing when the tab being viewed by the user is our site.

here is our current implementation in our react web app, in particular our attempt to not show the notification if the user is currently looking at our site.

  useEffect(() => {
    function foregroundWillDisplayListener (event) {
      console.log(event);
      //dont show notification if tab is currently being viewed
      if (document.visibilityState === 'visible') {
        return event.preventDefault();

      }
    }
        OneSignalDeferred.push(function () {
      OneSignal.Notifications.addEventListener("foregroundWillDisplay", foregroundWillDisplayListener);

    });

  }, []);

looking at foregroundWillDisplayListener event param I saw there are 2 params:

Error: Browser does not support preventing display.
    at Object.preventDefault (ServiceWorkerManager.js:168:27)
image

your time and assistance is highly appreciated.

Also apologies, this is duplicate ticket of #1676 on your react-native project, just realised this might be the right place to ask, thanks again.

jkasten2 commented 2 months ago

@thatop007 Thanks for reporting this issue!

At the time it wasn't clear if browsers could support this preventDefault() behavior when the site is in infocus / foregrounded. It seems it does, but we need to confirm and implement this in the SDK yet: