Detect availability of Notification API

This commit is contained in:
Adrian Gruntkowski 2024-12-01 15:09:06 +01:00
parent 97e5d9171d
commit f33eac82b8
3 changed files with 21 additions and 14 deletions

View file

@ -53,7 +53,7 @@
<button type="submit">Log out</button>
</form>
<div class="hidden">
<div id="notifications-pane" class="hidden">
<!-- Hidden for now, until push notifications are implemented -->
<button id="enable-notifications" class="hidden">
Enable notifications

View file

@ -2,6 +2,7 @@ import "./service-worker-init.js";
import { renderText } from "./dom.js";
import { SyncedNoteStore } from "./synced-store.js";
import {
notificationsAvailable,
authorizeNotifications,
notificationsEnabled,
sendNotification,
@ -57,21 +58,24 @@ if (!isLoggedIn) {
// Notifications API test - to be reused for push notifications later on
const notificationsButton = document.querySelector("#enable-notifications");
const notificationsTestButton = document.querySelector("#test-notifications");
if (notificationsAvailable()) {
document.querySelector("#notifications-pane").classList.remove("hidden");
const notificationsButton = document.querySelector("#enable-notifications");
const notificationsTestButton = document.querySelector("#test-notifications");
if (!notificationsEnabled()) {
if (!notificationsEnabled()) {
notificationsButton.classList.remove("hidden");
notificationsButton.addEventListener("click", () => {
authorizeNotifications(() => notificationsButton.classList.add("hidden"));
});
}
}
notificationsTestButton.addEventListener("click", () => {
notificationsTestButton.addEventListener("click", () => {
setTimeout(() => {
sendNotification("reminder", "This is a test reminder!");
}, 8000);
});
});
}
// There are two note-form component instances - one for
// composing new notes and another one for editing existing notes.

View file

@ -1,7 +1,10 @@
const notificationIcon = "/img/android-chrome-192x192.png";
export function notificationsAvailable() {
return !!window.Notification;
}
export function notificationsEnabled() {
return Notification.permission === "granted";
return window.Notification && Notification.permission === "granted";
}
export function authorizeNotifications(afterCallback) {