HTML5 Notification not working in Mobile Chrome

匿名 (未验证) 提交于 2019-12-03 03:03:02

问题:

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'); } 

回答1:

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 Nightly (but not Firefox beta yet).

(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).

https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration/showNotification has more info.

https://groups.google.com/a/chromium.org/forum/#!topic/blink-dev/BygptYClroM has info about why the Notification constructor is not supported in Chrome on Android though it still is in desktop Chrome.



回答2:

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



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!