9

我的網站使用它從來沒有在移動設備上工作桌面通知,但我最近開始收到以下異常在Chrome版本42.0.2311.108在Android 4.4:無法構造通知:非法構造

Failed to construct 'Notification': Illegal constructor. Use ServiceWorkerRegistration.showNotification() instead. TypeError: Failed to construct 'Notification': Illegal constructor. Use ServiceWorkerRegistration.showNotification() instead. 

我通知代碼很簡單,檢查用戶是否已授予的權限之後,我初始化一個新的Notification對象如下:

var notification = new Notification(messageOptions.title, { icon: messageOptions.icon }); 

如何更改此代碼使用ServiceWorkerRegistration.showNotification,其出現爲undefined,以支持Chrome移動版本中的通知,或者如果這不可行,則可以執行功能檢測並防止發生異常,如果這確實不被支持[還]。

+1

我只是把這個在一起,做這項工作爲你? http://jsbin.com/rexede/latest/quiet/ –

+0

您的示例中的相同錯誤消息。在桌面chrome上工作正常,但在android上失敗。 Android 5.1.0上的Chrome 42.0.2311.109; Nexus 5 Build/LMY47I – user1397423

回答

4

crbug.com/481856在Chrome問題跟蹤:

new Notification() is on the path to deprecation , because it implicitly assumes that the page will outlive the notification, which is very unlikely on mobile (and far from guaranteed on desktop too).

Hence we will never implement it on Android. We might one day remove it on desktop too, after a deprecation period.

Websites should use ServiceWorkerRegistration.showNotification() (see spec) instead whenever it is available.

The best way I can think of to feature-detect new Notification() is to try it (before you have permission) and catch the error:

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

You could then use it like this:

if (window.Notification && Notification.permission == 'granted') { 
    // We would only have prompted the user for permission if new 
    // Notification was supported (see below), so assume it is supported. 
    doStuffThatUsesNewNotification(); 
} else if (isNewNotificationSupported()) { 
    // new Notification is supported, so prompt the user for permission. 
    showOptInUIForNotifications(); 
}