forked from mattermost/mattermost-webapp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
notifications.jsx
70 lines (57 loc) · 2.18 KB
/
notifications.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import * as UserAgent from 'utils/user_agent.jsx';
import Constants from 'utils/constants.jsx';
import icon50 from 'images/icon50x50.png';
import iconWS from 'images/icon_WS.png';
let requestedNotificationPermission = false;
// showNotification displays a platform notification with the configured parameters.
//
// If successful in showing a notification, it resolves with a callback to manually close the
// notification. Notifications that do not require interaction will be closed automatically after
// the Constants.DEFAULT_NOTIFICATION_DURATION. Not all platforms support all features, and may
// choose different semantics for the notifications.
export async function showNotification({title, body, requireInteraction, silent, onClick} = {}) {
let icon = icon50;
if (UserAgent.isEdge()) {
icon = iconWS;
}
if (!('Notification' in window)) {
throw new Error('Notification not supported');
}
if (typeof Notification.requestPermission !== 'function') {
throw new Error('Notification.requestPermission not supported');
}
if (Notification.permission !== 'granted' && requestedNotificationPermission) {
throw new Error('Notifications already requested but not granted');
}
requestedNotificationPermission = true;
let permission = await Notification.requestPermission();
if (typeof permission === 'undefined') {
// Handle browsers that don't support the promise-based syntax.
permission = await new Promise((resolve) => {
Notification.requestPermission(resolve);
});
}
if (permission !== 'granted') {
throw new Error('Notifications not granted');
}
const notification = new Notification(title, {
body,
tag: body,
icon,
requireInteraction,
silent,
});
if (onClick) {
notification.onclick = onClick;
}
if (!requireInteraction) {
setTimeout(() => {
notification.close();
}, Constants.DEFAULT_NOTIFICATION_DURATION);
}
return () => {
notification.close();
};
}