Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 Notification not working in Mobile Chrome

I'm using the HTML5 notification API to notify the user in Chrome or Firefox. On desktop browsers, it works. However in Chrome 42 for Android, the permission is requested but the notification itself is not displayed.

The request code, works on all devices:

if ('Notification' in window) {   Notification.requestPermission(); } 

The sending code, works on desktop browser but not on mobile:

if ('Notification' in window) {   new Notification('Notify you'); } 
like image 479
Jorn Avatar asked Jul 20 '15 09:07

Jorn


People also ask

Do web push notifications work on mobile?

The web push channel is already supported by Android mobile devices, and it's in the works for iOS devices. Some browsers that currently support mobile push notifications include Chrome and Firefox on OS, Windows, OS X, Safari on OS X, and more.

How do I turn on notifications for a website on my phone?

To enable the browser notification on Android, you need to open settings>Apps & Notification. Now open the browser app and tap on the notification tab. At last turn on the notification by clicking on the Show notification.


2 Answers

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.

like image 161
sideshowbarker Avatar answered Oct 04 '22 23:10

sideshowbarker


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

like image 40
Kalimah Avatar answered Oct 05 '22 00:10

Kalimah