检查浏览器通知是否可用

问题描述 投票:0回答:3

我正在处理浏览器通知,因为它不适用于每个浏览器,所以我想检查我的 JS 代码(如果可用)。

我查看了 Mozilla 开发者部分:
https://developer.mozilla.org/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API

他们告诉我应该使用此代码来检查浏览器是否支持通知:

  if (!("Notification" in window)) {
    alert("This browser does not support system notifications");
  }

我将该代码复制到我的网站中;该通知在之前工作的浏览器中仍然有效,但它会阻止其他代码的执行(就像在“检查”代码之前所做的那样)。

例如:在边缘浏览器中,我收到控制台错误:

 'Notification is undefined'

那么您首选的方法来检查浏览器是否具有通知功能?

javascript browser notifications
3个回答
20
投票

以下代码将检查浏览器是否与网络通知API兼容

if ('Notification' in window) {
  // API supported
} else {
  // API not supported
}

6
投票

您还应该检查前缀版本:

var NotificationIsSupported = !!(window.Notification /* W3C Specification */ || window.webkitNotifications /* old WebKit Browsers */ || navigator.mozNotification /* Firefox for Android and Firefox OS */)

您可以在本文中阅读有关如何执行此操作的更多信息。文章还有很多如何支持其他设备的代码示例。


0
投票

您使用什么浏览器大多数浏览器应该支持通知

顺便说一下,我正在尝试为一个名为 lichess 的网站获取有关 safari 的通知

© www.soinside.com 2019 - 2024. All rights reserved.