无法构造通知:非法构造函数

Sig*_*ard 17 javascript mobile android google-chrome html5-notifications

我的网站使用的桌面通知从未在移动设备上运行,但我最近在Android 4.4上的Chrome版本42.0.2311.108中开始收到以下例外:

Failed to construct 'Notification': Illegal constructor. Use ServiceWorkerRegistration.showNotification() instead. TypeError: Failed to construct 'Notification': Illegal constructor. Use ServiceWorkerRegistration.showNotification() instead.
Run Code Online (Sandbox Code Playgroud)

我的通知代码很简单,在检查用户是否已授予权限后,我按如下方式初始化新的Notification对象:

var notification = new Notification(messageOptions.title, { icon: messageOptions.icon });
Run Code Online (Sandbox Code Playgroud)

如何更改此代码以使用ServiceWorkerRegistration.showNotification(undefined用于支持Chrome移动版中的通知),或者如果不可能,则执行功能检测并防止异常发生,如果这不是支持[尚].

Mat*_*unt 12

请参阅Chrome问题跟踪器上的crbug.com/481856:

new Notification()在弃用的路径上,因为它隐含地假设页面将比通知更长,这在移动设备上是不太可能的(并且在桌面上也远远不能保证).

因此,我们永远不会在Android上实现它.在弃用期之后,我们可能有一天会在桌面上删除它.

网站应该在可用时使用ServiceWorkerRegistration.showNotification()(参见规范).

我能想到的特征检测的最佳方法new Notification()是尝试它(你获得许可之前)并捕获错误:

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;
}
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样使用它:

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();
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,链接的 Chrome 问题已同时[更新](https://github.com/whatwg/notifications/issues/26#issuecomment-126310459),现在显示“看来我们正在保留非持久通知。” ` (2认同)