22

我正在使用HTML5 notification API在Chrome或Firefox中通知用戶。在桌面瀏覽器上,它可以工作。但是,在Android版Chrome 42中,請求權限,但通知本身未顯示。HTML5通知無法在移動Chrome中使用

請求的代碼,適用於所有設備:

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

發送代碼,適用於桌面瀏覽器,但無法在手機上:

if ('Notification' in window) { 
    new Notification('Notify you'); 
} 
+1

我確切地說同樣的問題。還嘗試過'window.webkitNotification'。 *推送通知*,另一方面,工作,但完全是一個不同的野獸:https://developers.google.com/web/updates/2015/03/push-notificatons-on-the-open-web?hl = en(演示https://simple-push-demo.appspot.com/) – BoppreH

回答

29

嘗試以下操作:

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

這應該可以在Chrome和Firefox每晚的Android上運行(但不是Firefox beta版)。

(該sw.js文件可以僅僅是一個零字節文件。)

一個需要注意的是,你必須從一個安全的起源運行它(一個https URL,而不是http URL)。

https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration/showNotification有更多信息。

https://groups.google.com/a/chromium.org/forum/#!topic/blink-dev/BygptYClroM有關於爲什麼Notification構造函數在Android版Chrome中不受支持的信息,儘管它仍在桌面版Chrome中。

+1

這可以工作,但會創建具有自己生命週期的後臺ServiceWorker。我希望有一個更輕量級的解決方案,但是哦。感謝您的答覆。 – BoppreH

+3

關於擁有更輕量級的解決方案(不需要ServiceWorker),我建議花時間在https://github.com/whatwg/notifications/issues上提出問題。人們非常希望真實世界的網頁開發人員提供反饋,根據我的經驗,他們會對他們獲得的反饋作出高度響應。但是沒有任何人發送反饋,它不太可能會有任何改變。 – sideshowbarker

+5

建議的解決方案不會處理點擊事件,儘管這可能與light API在Android中不可用的原因相同。不能保證頁面會在點擊通知時出現(因爲它可以在任何時候被內存管理器殺死),所以這會導致一個超級片狀的API。 –

2

運行這段代碼:

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

控制檯在Chrome DevTools顯示了這個錯誤:

Uncaught TypeError: Failed to construct ‘Notification’: Illegal constructor. Use ServiceWorkerRegistration.showNotification() instead

更好的方法可能是:

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

功能來源:HTML5Rocks