Home > Blockchain >  Problem with service worker JavaScript on mobile browsers
Problem with service worker JavaScript on mobile browsers

Time:11-14

This is driving me crazy. I have been trying to implement push notifications for a website and I found a solution (Javacript API notification). The thing is: notifications are not working on mobile devices.

I read about service workers and I have been using this code to ask user for permission and everything, but it is still not working. I am not sure if I am doing something wrong or what. I read about it has to be an https site, but that's does not seem to be the problem. I have also tried the push.js plugin plugin.js, but no succeed so far (even when the demo of that plugin that it's in their website is working on my mobile browser) This is the website >>> https://park-inside.nl/test/

The "Set notification" button is meant to show a notification when the waiting time is below the selected time. So, to test this, just click "Set notification", then select minutes greater than the "Wachttijd" column and refresh page. The notification should appear. It works on desktop browser, but not on mobile. Any idea or suggestion? I would love and appreciate any help.

Note: I am using Chrome 94 on Android 9 (go)

Code that ask for user permission:

Notification.requestPermission(function(result) {
    if (result === 'granted') {
        navigator.serviceWorker.ready.then(function(registration) {
            registration.showNotification('Notification with ServiceWorker');
        });
    }
});

CodePudding user response:

See the browser support table for Web Notifications: https://caniuse.com/notifications.

They only work in Chrome on Android, not in the stock Android Browser.

Also, be sure to register a service worker, even if it's an empty one, as seen here: https://stackoverflow.com/a/31787926/10551293.

A demo of the notifications is available here: https://serviceworke.rs/push-payload_demo.html.

Google also has a step-by-step codelab available here: https://developers.google.com/codelabs/pwa-training/pwa03--going-offline#0

CodePudding user response:

Apparently, I had to first do this to register a service worker:

if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('sw.js');
}

I am not really sure, but I was trying to user a route for the 'sw.js' file, like this: js/sw.js. When I placed that file in the root of the project, it worked. Also, I added this code to that file to log in the console:

self.addEventListener('install', (event) => {
    console.log('Installed');
});

self.addEventListener('activate', (event) => {
    console.log('Activated');
});

self.addEventListener('fetch', (event) => {
    console.log('Fetch request');
});

Thanks to swift-lunx for the links to some documentation, where I found a solution:

https://developers.google.com/web/ilt/pwa/introduction-to-push-notifications

  • Related