skip to Main Content

I have the following test html with javascript, where the main interest is about notifications :

<head>
    <title>Test Notifications</title>

</head>
<body>


    <div >
        <button  style="margin: 0;position: absolute;top: 50%;left: 50%;-ms-transform: translate(-50%, -50%);transform: translate(-50%, -50%);" 
                 onclick="askPermissionsAndSendNotification();"  >Send Notification</button>

    </div>


    <script type="text/javascript"   >
        function askPermissionsAndSendNotification() {

            if (!window.Notification) {
                return false;
            } else {
                if (Notification.permission === 'default') {
                    Notification.requestPermission(function (p) {
                        if (p !== 'denied') {
                            sendNotification();
                        }
                    })
                } else {
                    sendNotification();
                }
            }
        }

        function sendNotification() {
            let title = "Test notification";
            let message = "Test notification content";
            let  myNotification = new Notification(title, {
                body: message
            });
            myNotification.addEventListener('click', function () {
                window.open("https://stackoverflow.com/","_blank");
            });
        }
    </script>

</body>

Is a simple notification , we send it by clicking on the button , and will open a new tab with an url . Everything works perfect until refresh.

If you have a notification not closed, if you refresh the page ,whatever will be code in your click event, the notification will open a new page with your website base url . I assume the listener is destroyed on page refresh, probably this is the default behaviour . Can something be done to have the original notification onclick action called after a page refresh if notification is created before the refresh ?

2

Answers


  1. Perhaps you can save the notification inside local storage.
    https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem

    localStorage.setItem("notification", JSON.stringify({title,message}));
    

    And later on inside an IIFE get the item that you want https://developer.mozilla.org/en-US/docs/Glossary/IIFE.

    (() => {
        const item = JSON.parse(localStorage.getItem('notification'));
        // Your logic below...
    })();
    

    Now you also need something to differentiate which item you want to save to local storage, because if you use the setItem above, every time you push a notification it will be pushed to storage.

    Login or Signup to reply.
  2. Notifications in the browser are non-persistent which causes them to stop working whenever you close your tab. You’ll need to move your logic to a Service Worker to be able to use persistent notifications. Service Workers will run regardless of opened or closed tabs after they’ve been installed.

    First start of by registering your Service Worker. Then modify the sendNotification function. We want to let the function send a message to the Service Worker with the information that your notification needs, instead of creating a Notification ourselfs, then the worker will be in charge of creating the notification.

    Messages can be sent to a Service Worker with the postMessage method of the current registered worker. You can also send the URL you want the user to redirect to when clicking.

    // app.js
    navigator.serviceWorker.register('serviceworker.js');
    
    async function sendNotification() {
      let title = "Test notification";
      let message = "Test notification content";
      const url = "https://stackoverflow.com/";
    
      // Wait until the Service Worker ready.
      const registration = await navigator.serviceWorker.ready;
    
      // Send a message over to the worker.
      registration.active.postMessage({
        title,
        message,
        url
      })
    }
    

    On the Service Worker side you’ll want first want to be able to receive any incoming message we send from the client. Listen for the message event and handle your received data from there. The Service Worker registration has a built in method called showNotification which does exactly the same as new Notification(). Pass your data to the method.

    Then listen for the notificationclick event. Here you can handle whatever needs to happen when the user clicks the notification. From here you can access the url and open a new browser window with the openWindow() method of the Clients interface.

    // serviceworker.js
    addEventListener('message', ({ data }) => {
      // Deconstruct received data.
      const {
        title,
        message,
        url
      } = data;
    
      // Show notification with the received data.
      registration.showNotification(title, {
        body: message,
        data: {
          url
        }
      });
    })
    
    addEventListener('notificationclick', async (event) => {
      event.notification.close();
    
      const { url } = event.notification.data;
      const openPage = clients.openWindow(url);
      event.waitUntil(openPage);
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search