Skip to content

Commit 482590a

Browse files
authored
Merge pull request #998 from Patternslib/push-optimizations
pat-push: Add support for desktop notifications
2 parents 11189d4 + 009b7a9 commit 482590a

File tree

1 file changed

+47
-2
lines changed

1 file changed

+47
-2
lines changed

src/pat/push/push.js

Lines changed: 47 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,14 @@ import "regenerator-runtime/runtime"; // needed for ``await`` support
22
import Base from "../../core/base";
33
import logging from "../../core/logging";
44
import Parser from "../../core/parser";
5+
import registry from "../../core/registry";
56

67
const logger = logging.getLogger("push");
78

89
export const parser = new Parser("push");
910
parser.addArgument("url", null);
1011
parser.addArgument("push-id", null);
11-
parser.addArgument("mode", "replace");
12+
parser.addArgument("mode", "replace", ["replace", "append", "desktop-notification"]);
1213

1314
export default Base.extend({
1415
name: "push",
@@ -20,7 +21,9 @@ export default Base.extend({
2021
logger.debug("received push marker");
2122
const data = e?.detail?.body;
2223
if (data === this.options.pushId) {
23-
if (this.el.tagName === "FORM") {
24+
if (this.options.mode === "desktop-notification") {
25+
this.desktop_notification();
26+
} else if (this.el.tagName === "FORM") {
2427
this.el.submit();
2528
} else {
2629
this.perform_inject();
@@ -38,6 +41,48 @@ export default Base.extend({
3841
} else {
3942
this.el.innerHTML = data;
4043
}
44+
registry.scan(this.el);
45+
} catch (e) {
46+
logger.error(
47+
`Could not fetch from ${this.options.url} on push-id ${this.options.pushId}.`
48+
);
49+
}
50+
},
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+
}
4186
} catch (e) {
4287
logger.error(
4388
`Could not fetch from ${this.options.url} on push-id ${this.options.pushId}.`

0 commit comments

Comments
 (0)