From 47f06b2a2a3edc87f1fa8c972d03477ec3430396 Mon Sep 17 00:00:00 2001 From: Adrian Gruntkowski Date: Sat, 16 Nov 2024 00:29:09 +0100 Subject: [PATCH] Test notifications API --- index.html | 5 ++++- js/jenot.js | 21 +++++++++++++++++++++ js/notifications.js | 22 ++++++++++++++++++++++ 3 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 js/notifications.js diff --git a/index.html b/index.html index a6ae658..c9f065f 100644 --- a/index.html +++ b/index.html @@ -30,6 +30,9 @@

Jenot

+ + +

@@ -37,7 +40,7 @@

- +
diff --git a/js/jenot.js b/js/jenot.js index f080690..6a93e48 100644 --- a/js/jenot.js +++ b/js/jenot.js @@ -2,8 +2,29 @@ import "./service-worker.js"; import { renderText } from "./dom.js"; import { NoteStore } from "./store.js"; import { DBNoteStore } from "./db-store.js"; +import { + authorizeNotifications, + notificationsEnabled, + sendNotification, +} from "./notifications.js"; import "./components.js"; +const notificationsButton = document.querySelector("#enable-notifications"); +const notificationsTestButton = document.querySelector("#test-notifications"); + +if (!notificationsEnabled()) { + notificationsButton.classList.remove("hidden"); + notificationsButton.addEventListener("click", () => { + authorizeNotifications(() => notificationsButton.classList.add("hidden")); + }); +} + +notificationsTestButton.addEventListener("click", () => { + setTimeout(() => { + sendNotification("reminder", "This is a test reminder!"); + }, 8000); +}); + const urlParams = new URLSearchParams(window.location.search); const Notes = urlParams.has("localStorage") diff --git a/js/notifications.js b/js/notifications.js new file mode 100644 index 0000000..f116c20 --- /dev/null +++ b/js/notifications.js @@ -0,0 +1,22 @@ +const notificationIcon = "/img/android-chrome-192x192.png"; + +export function notificationsEnabled() { + return Notification.permission === "granted"; +} + +export function authorizeNotifications(afterCallback) { + Notification.requestPermission(function (permission) { + sendNotification( + "notification", + "Jenot can now send you alerts about reminders!", + ); + afterCallback(); + }); +} + +export function sendNotification(titleSuffix, message) { + return new Notification(`Jenot ${titleSuffix}`, { + body: message, + icon: notificationIcon, + }); +}