Skip to content

Commit 009b7a9

Browse files
committed
feat(pat push): Add support for desktop notifications.
1 parent 8c75fa1 commit 009b7a9

File tree

1 file changed

+45
-2
lines changed

1 file changed

+45
-2
lines changed

src/pat/push/push.js

Lines changed: 45 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ const logger = logging.getLogger("push");
99
export const parser = new Parser("push");
1010
parser.addArgument("url", null);
1111
parser.addArgument("push-id", null);
12-
parser.addArgument("mode", "replace");
12+
parser.addArgument("mode", "replace", ["replace", "append", "desktop-notification"]);
1313

1414
export default Base.extend({
1515
name: "push",
@@ -21,7 +21,9 @@ export default Base.extend({
2121
logger.debug("received push marker");
2222
const data = e?.detail?.body;
2323
if (data === this.options.pushId) {
24-
if (this.el.tagName === "FORM") {
24+
if (this.options.mode === "desktop-notification") {
25+
this.desktop_notification();
26+
} else if (this.el.tagName === "FORM") {
2527
this.el.submit();
2628
} else {
2729
this.perform_inject();
@@ -46,4 +48,45 @@ export default Base.extend({
4648
);
4749
}
4850
},
51+
52+
async desktop_notification() {
53+
try {
54+
const response = await fetch(this.options.url);
55+
const data = await response.json();
56+
57+
if (data.length === 0) {
58+
return;
59+
}
60+
61+
// Let's check if the browser supports notifications
62+
if (!("Notification" in window)) {
63+
logger.error("This browser does not support notifications.");
64+
return;
65+
}
66+
67+
// Notifications need to be granted.
68+
// Note: Current browsers don't allow an automatic request for
69+
// permission but need an interaction to allow it.
70+
// The following code won't work out of the box in such cases.
71+
if (!(Notification.permission in ["denied", "granted"])) {
72+
Notification.requestPermission((permission) => {
73+
// Whatever the user answers, we make sure Chrome stores the information
74+
if (!("permission" in Notification)) {
75+
Notification.permission = permission;
76+
}
77+
});
78+
}
79+
80+
// Let's check if the user is okay to get some notification
81+
if (Notification.permission === "granted") {
82+
for (const message of data) {
83+
new Notification(message.title, message);
84+
}
85+
}
86+
} catch (e) {
87+
logger.error(
88+
`Could not fetch from ${this.options.url} on push-id ${this.options.pushId}.`
89+
);
90+
}
91+
},
4992
});

0 commit comments

Comments
 (0)