This example would leave a permission or a service worker on this site, so it opens on its own, in a new tab.

Open in a new tab

Ask for notification permission on a click, follow the permission live, and send a reminder as a system notification, or show it in the page when that is not possible.

Uses @awacloud/fw (Apache-2.0). This example's code is Apache-2.0.

When to use it

Something the user asked to hear about while the page is open in a background tab: a reminder, a finished export, a message. Push notifications to a closed page need a service worker and a push server, outside this example.

Copy-paste steps

  1. npm install @awacloud/fw
  2. Serve node_modules/@awacloud/fw/src/ at /vendor/fw/ (node serve.js from the examples root does this; any static server works). Notifications need https or localhost.
  3. Copy index.html and main.js next to each other and open index.html through that server. The ../../_style/examples.css link is optional: copy that file along, or delete the link.

What it shows

  • notifications.permission() on load, notifications.requestPermission() only from the form's submit: browsers may block or quiet sites that ask before the user did anything.
  • permissions.watch('notifications', callback): the line at the top follows the user changing the permission in the site settings, without a reload.
  • notifications.show(title, { body, autoCloseMs, onclick }): closes itself after 10 s; a click brings the page to the front.
  • show() throws unless the permission is granted, and Chrome on Android throws for any page notification (it notifies only from a service worker, notifications.showFromSW). The page catches both and shows the reminder in the page instead.
  • The two APIs name the states differently (default and prompt); the page maps both to one wording.

Code

main.js

javascriptApache-2.040 lines

// SPDX-License-Identifier: Apache-2.0
import fw from '@awacloud/fw';
import { notifications } from '@awacloud/fw/dom/utils/notifications.js';
import { permissions } from '@awacloud/fw/dom/utils/permissions.js';

fw.runtime.registerAllDeep([notifications, permissions]);
const NOTIFY = fw.runtime.resolve('notifications');
const PERMISSIONS = fw.runtime.resolve('permissions');

/** @param {string} id */
const el = (id) => /** @type {HTMLInputElement} */ (document.getElementById(id));
/** The two APIs name the states differently; the page says them one way. */
const STATES = { default: 'not asked yet', prompt: 'not asked yet', granted: 'allowed', denied: 'blocked' };
/** @param {string} state */
const showState = (state) => { el('permission').textContent = STATES[/** @type {keyof STATES} */ (state)] ?? state; };

// The current state, then live changes (the user can change it in the site settings at any time).
showState(NOTIFY.isSupported() ? NOTIFY.permission() : 'denied');
if (PERMISSIONS.isSupported()) PERMISSIONS.watch('notifications', showState, () => {});

/** Deliver the reminder: a system notification if allowed, else in the page. @param {string} text */
function remind(text) {
    try {
        // show() throws unless allowed; Chrome on Android also throws: it notifies only from a service worker.
        NOTIFY.show('Reminder', { body: text, autoCloseMs: 10_000, onclick: () => window.focus() });
        el('status').textContent = `Reminder sent: ${text}`;
    } catch {
        el('status').textContent = `Reminder (shown here, no notification): ${text}`;
    }
}

el('form').addEventListener('submit', async (event) => {
    event.preventDefault();
    const text = el('what').value;
    const seconds = el('seconds').valueAsNumber;
    // Ask on a click, never on page load: a browser may block sites that ask unprompted.
    if (NOTIFY.isSupported() && NOTIFY.permission() === 'default') showState(await NOTIFY.requestPermission());
    el('status').textContent = `Reminding you in ${seconds} s.`;
    setTimeout(() => remind(text), seconds * 1000);
});

index.html

htmlApache-2.029 lines

<!doctype html>
<!-- SPDX-License-Identifier: Apache-2.0 -->
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>fw · Send a reminder as a notification</title>
  <link rel="stylesheet" href="../../_style/examples.css">
  <script type="importmap">
  { "imports": {
    "@awacloud/fw": "/vendor/fw/main.js", "@awacloud/fw/": "/vendor/fw/" } }
  </script>
  <script type="module" src="./main.js"></script>
</head>
<body>
  <main>
    <h1>Send a reminder as a notification</h1>
    <p>Notifications for this page: <strong id="permission"></strong></p>
    <form id="form">
      <label for="what">Remind me to</label>
      <input id="what" type="text" value="stretch my legs" required>
      <label for="seconds">in (seconds)</label>
      <input id="seconds" type="number" min="1" max="600" value="5" required>
      <button type="submit">Set the reminder</button>
    </form>
    <p id="status" role="status"></p>
  </main>
</body>
</html>