Check if browser notification is available
Asked Answered
S

2

9

I am working with browser notifications and because it is not available for every browser I want to check in my JS-code, if it is available.

I took a look in the Mozilla developer section:
https://developer.mozilla.org/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API

They tell me that I should use this code to check whether a browser has notification support or not:

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

I copied that code into my website; the notification still works in the browsers where it worked before but it blocks the execution of other code (as it did before the 'check'-code).

For example: in the edge browser, I get the console error:

 'Notification is undefined'

So what is the preferred method from you to check whether a browser has notification capability?

Spoony answered 17/7, 2016 at 14:32 Comment(2)
If ("Notification" in window) is false, then your code has to avoid using any of the APIs.Homogamy
Sorry, my fault! I have to check that twice in my code and i missed one.Spoony
M
22

The following code would check whether the browser is compatible with the web notification API

if ('Notification' in window) {
  // API supported
} else {
  // API not supported
}
Meaghan answered 17/7, 2016 at 14:38 Comment(1)
@JeroenVannevel the code is checking if the global window object has Notification as a property on it. If it does, then the current browser does support the Notification API.Barye
B
6

You should also check for the prefixed versions:

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

You can read more on how to do this in this article. The article also has a lot of code examples of how to support other devices.

Balsamiferous answered 17/7, 2017 at 9:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.