HTML5 Notifications with Service Workers on Chrome Mobile not working

i am using HTML5 Desktop Notifications in my application. But i have a problem with Google Chrome Mobile. As far as i have read, i need to use Service Workers to create a new Notification on Chrome Mobile, because the browser is treating them differently (HTML5 Notification not working in Mobile Chrome). I tried to integrate the example (and some more variations) of the following Stack Overflow Question but i am not able to get it running. He is never reaching the .showNotification method in the serviceWorker. I have never worked with Service Workers before, so i have no idea what i need to do, to get them working. Do i need to put this sw.js file somewhere in the project? My app is a Java Spring Project and i don’t know where i would have to put this .js file. I put it in the root directory of the project and in the same directory where the file with this code is, but there was no difference. So if anybody could help me, that would be nice. If more code or project structure is needed for answering the question i can provide more.

if (!("Notification" in window)) {
    } else if (Notification.permission === "granted"){
         var localUserSettings = new LocalUserSettings(loggedInUser);
         if (localUserSettings.notificationRights == "granted"){
                try{
                    var notification = new Notification( s, {
                        body: t, 
                        icon : "/image/" + id,
                        lang: "de",
                        tag: notificationId
                    });
                    setTimeout(function(){
                        notification.close();
                    }, 10000);
                } catch (e){
                    if ('serviceWorker' in navigator) {
                        navigator.serviceWorker.register('sw.js').then(function(registration) {
                            registration.showNotification(s, {
                              body: t,
                              icon: "/image/" + id,
                              vibrate: [200, 100, 200, 100, 200, 100, 200],
                              tag: notificationId
                            });
                        });
                    }

                }
         }
     }

Thanks 🙂

Edit: And yes, i am running the code from a secured origin (https)


Source: html5

Leave a Reply