void-mail icon indicating copy to clipboard operation
void-mail copied to clipboard

Click on notifications opens login page

Open synox opened this issue 6 years ago • 1 comments

We want the page to be reloaded. But then when clicking the notification, the browser can not find the tab (because it was replaced) and will open a new one at /.

Options:

  • remove Notifications
  • dont make reload
  • ...?

synox avatar Mar 23 '19 01:03 synox

POC from https://web-push-book.gauntface.com/chapter-05/02-display-a-notification/

service-worker.js

  const examplePage = '/demos/notification-examples/example-page.html';

  function focusWindow(event) {
    const urlToOpen = new URL(examplePage, self.location.origin).href;
    const promiseChain = clients.matchAll({
      type: 'window',
      includeUncontrolled: true
    })
    .then((windowClients) => {
      let matchingClient = null;

      for (let i = 0; i < windowClients.length; i++) {
        const windowClient = windowClients[i];
        if (windowClient.url === urlToOpen) {
          matchingClient = windowClient;
          break;
        }
      }

      if (matchingClient) {
        return matchingClient.focus();
      } else {
        return clients.openWindow(urlToOpen);
      }
    });

    event.waitUntil(promiseChain);
  }

  self.addEventListener('notificationclick', function(event) {
    event.notification.close();
    focusWindow(event);
  });

  self.addEventListener('notificationclose', function(event) {
    const dismissedNotification = event.notification;
    event.waitUntil(Promise.resolve());
  });

index.html

  <!DOCTYPE html>
  <html>
  <body>
        <button onclick="mybutton()">Focus a Window OR Open</button>

    <script type="text/javascript">
      function registerServiceWorker() {
      return navigator.serviceWorker.register('service-worker.js')
      .then(function(registration) {
        console.log('Service worker successfully registered.');
        return registration;
      })
      .catch(function(err) {
        console.error('Unable to register service worker.', err);
      });
    }

      window.addEventListener('load', function() {

      return registerServiceWorker()
      .then(function(registration) {
        window.registration = registration
        navigator.serviceWorker.addEventListener('message', function(event) {
          console.log('Received a message from service worker: ', event.data);
          });  
        })
      })



      function mybutton(){
        const options = {
          body: 'Clicking on this notification will focus on an open window ' +
            'otherwise open a new one.',
          tag: 'focus-window'
        };
        registration.showNotification('Focus or Open a Window', options);
      
    };
    </script>
   
  </body>
  </html>

synox avatar Apr 13 '19 11:04 synox