【问题标题】:Failed to construct Notification: Illegal constructor构造通知失败:构造函数非法
【发布时间】:2015-06-28 18:27:51
【问题描述】:

我的网站使用从未在移动设备上运行过的桌面通知,但我最近开始在 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.

我的通知代码很简单,在检查用户是否授予权限后,我初始化一个新的通知对象,如下所示:

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

如何更改此代码以使用显示为 undefined 的 ServiceWorkerRegistration.showNotification 来支持移动版 Chrome 中的通知,或者如果无法执行功能检测并防止发生异常如果 [还] 确实不支持。

【问题讨论】:

  • 我只是把这个放在一起,这对你有用吗? jsbin.com/rexede/latest/quiet
  • 与您的示例相同的错误消息。在桌面 chrome 上工作正常,但在 android 上失败。 Android 5.1.0 上的 Chrome 42.0.2311.109; Nexus 5 构建/LMY47I

标签: javascript android google-chrome mobile html5-notifications


【解决方案1】:

在 Chrome 问题跟踪器上查看 crbug.com/481856

new Notification()on the path to deprecation,因为它隐含地假定页面将比通知更有效,这在移动设备上是不太可能的(在桌面设备上也远不能保证)。

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

网站应使用ServiceWorkerRegistration.showNotification() (see spec) 代替,只要它可用。

我能想到的对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;
}

你可以这样使用它:

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

【讨论】:

  • 请注意,链接的 Chrome 问题在此期间一直是 updated,现在显示为 It seems we're keeping non-persistent notifications.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-23
  • 2011-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
相关资源
最近更新 更多