HTML5 Notification not working in Mobile Chrome
Try the following:
navigator.serviceWorker.register('sw.js');Notification.requestPermission(function(result) { if (result === 'granted') { navigator.serviceWorker.ready.then(function(registration) { registration.showNotification('Notification with ServiceWorker'); }); }});
That should work on Android both in Chrome and in Firefox (and on iOS in Safari, too).
(The sw.js
file can just be a zero-byte file.)
One caveat is that you must run it from a secure origin (an https
URL, not an http
URL).
See https://developer.mozilla.org/docs/Web/API/ServiceWorkerRegistration/showNotification.
Running this code:
if ('Notification' in window) { Notification.requestPermission();}
Console in Chrome DevTools shows this error:
Uncaught TypeError: Failed to construct ‘Notification’: Illegal constructor. Use ServiceWorkerRegistration.showNotification() instead
A better approach might be:
function isNewNotificationSupported() { if (!window.Notification || !Notification.requestPermission) return false; if (Notification.permission == 'granted') throw new Error('You must only call this \*before\* calling Notification.requestPermission(), otherwise this feature detect would bug the user with an actual notification!'); try { new Notification(''); } catch (e) { if (e.name == 'TypeError') return false; } return true; }
Function Source: HTML5Rocks
If you already have a service worker registered, use this:
navigator.serviceWorker.getRegistrations().then(function(registrations) { registrations[0].showNotification(title, options);});