-
Notifications
You must be signed in to change notification settings - Fork 0
/
notify.js
101 lines (90 loc) · 2.41 KB
/
notify.js
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
(function(Scratch) {
'use strict';
let denied = false;
/** @type {Notification|null} */
let notification = null;
const askForNotificationPermission = async () => {
try {
// @ts-expect-error - canNotify is too old.
const allowedByVM = await Scratch.canNotify();
if (!allowedByVM) {
throw new Error('Denied by VM');
}
const allowedByBrowser = await Notification.requestPermission();
if (!allowedByBrowser) {
throw new Error('Denied by browser');
}
denied = false;
return true;
} catch (e) {
denied = true;
console.warn('Could not request notification permissions', e);
return false;
}
};
class Notifications {
getInfo() {
return {
id: 'mdwaltersnotifications',
name: 'Notifications',
blocks: [
{
opcode: 'requestPermission',
blockType: Scratch.BlockType.COMMAND,
text: 'request notification permission'
},
{
opcode: 'hasPermission',
blockType: Scratch.BlockType.BOOLEAN,
text: 'has notification permission'
},
{
opcode: 'showNotification',
blockType: Scratch.BlockType.COMMAND,
text: 'create notification with text [text] and title [title]',
arguments: {
text: {
type: Scratch.ArgumentType.STRING,
defaultValue: 'Text'
},
title: {
type: Scratch.ArgumentType.STRING,
defaultValue: 'Title'
}
}
},
{
opcode: 'closeNotification',
blockType: Scratch.BlockType.COMMAND,
text: 'close notification'
}
]
};
}
requestPermission() {
return askForNotificationPermission();
}
hasPermission() {
if (denied) {
return false;
}
return askForNotificationPermission();
}
async _showNotification(text,tite) {
if (await this.hasPermission()) {
notification = new Notification(tite, {
body: text
});
}
}
showNotification(body,title) {
this._showNotification(body,title);
}
closeNotification() {
if (notification) {
notification.close();
}
}
}
Scratch.extensions.register(new Notifications());
})(Scratch);