Emmanuel Akinfulubi

JavaScriptEvents

Show a desktop notification in JavaScript

Advanced · 4 min read

A chat app pings you when a message arrives. A booking site tells you your bus is about to leave. Those pop-ups outside the page come from the browser's Notification API. Before a site can show one, it must ask the user's permission, and how and when you ask decides whether you ever get it.

In this tutorial you will write a notify function that checks the permission, asks for it only when it makes sense, sends a notification, and explains what happened in every case. You should have used async, await and try/catch.

The three permission states

Notification.permission is always one of three strings:

  • 'default': the user hasn't been asked yet, or closed the prompt without choosing.
  • 'granted': they said yes. You can show notifications.
  • 'denied': they said no.

Notification.requestPermission() shows the prompt and returns a promise that resolves to the new state.

A refusal is final

Once the permission is 'denied', the browser never shows the prompt again. requestPermission() resolves to 'denied' straight away, with no dialog. Only the user can change it, in the browser's site settings. So check for 'denied' first, and when you find it, tell the user instead of appearing to try.

For this lesson, Notification is a stand-in that starts at 'default' and says yes when asked.

Here is the exercise. Try it yourself first, or read on and we will build it together.

21 Send a desktop notification, with permission

hard

Ask for notification permission and then send one. Handle all three permission states, and do not ask at the wrong moment.

Stuck? Three hints, smallest first
  1. 1. Notification.permission is ‘default’, ‘granted’ or ‘denied’.
  2. 2. requestPermission() returns a promise. Once denied, asking again does nothing.
  3. 3. Constructing a Notification without permission throws, so check first.

Step 1: read the current state

Step 1

console.log(typeof Notification); // function
console.log(Notification.permission); // default

Notification is a constructor: you make a notification with new Notification(title, options). In a browser without the API, typeof Notification would be 'undefined', which is an easy way to check for support before using it.

Step 2: handle a refusal first

The function takes Notification as its first argument. In the page you pass the real one; in a test you can pass a pretend one in any state.

Step 2

async function notify(Notification, title, body) {
  if (Notification.permission === 'denied') {
    return { state: 'denied', message: 'Permission was refused earlier. The browser will not ask again.' };
  }
  return { state: 'unfinished' };
}
const blocked = { permission: 'denied', requestPermission: async () => 'denied' };
console.log((await notify(blocked, 'Bus departing', '')).message); // Permission was refused earlier. The browser will not ask again.
console.log(await blocked.requestPermission()); // denied

blocked is a pretend Notification in the 'denied' state. Asking it again gives 'denied' immediately, as a real browser would. Checking first means we don't pretend to ask.

Step 3: ask when the state is default

Step 3

async function notify(Notification, title, body) {
  if (Notification.permission === 'denied') {
    return { state: 'denied', message: 'Permission was refused earlier. The browser will not ask again.' };
  }
  if (Notification.permission === 'default') {
    const answer = await Notification.requestPermission();
    if (answer !== 'granted') {
      return { state: answer, message: `Not granted: "${answer}". Nothing sent.` };
    }
  }
  return { state: 'ready' };
}
const refuses = { permission: 'default', requestPermission: async () => 'denied' };
console.log((await notify(refuses, 'Bus departing', '')).message); // Not granted: "denied". Nothing sent.

If the user hasn't been asked, we ask, and wait for the answer. A "no" ends it with a clear message. If the state was already 'granted', both ifs are skipped and we go straight on.

Step 4: send it

Step 4

async function notify(Notification, title, body) {
  if (Notification.permission === 'denied') {
    return { state: 'denied', message: 'Permission was refused earlier. The browser will not ask again.' };
  }
  if (Notification.permission === 'default') {
    const answer = await Notification.requestPermission();
    if (answer !== 'granted') {
      return { state: answer, message: `Not granted: "${answer}". Nothing sent.` };
    }
  }
  try {
    new Notification(title, { body });
    return { state: 'sent', message: 'Sent.' };
  } catch (error) {
    return { state: 'error', message: `Could not send: ${error.name}` };
  }
}
const result = await notify(Notification, 'Bus departing', 'Ojota to Abuja, 14 seats left');
console.log(result.state, Notification.permission); // sent granted
console.log(Notification.shown); // [{ title: 'Bus departing', body: 'Ojota to Abuja, 14 seats left' }]

new Notification(title, { body }) shows the notification: a title, plus a line of text under it. (Notification.shown is not part of the real API. It's how the stand-in lets us see what would have appeared.)

The try/catch is there because creating a notification can fail. The full solution's stand-in throws a TypeError if you create one without permission. Real browsers differ in how they report problems, so the safe rule is the same everywhere: check the permission first, and keep the try/catch for anything unexpected.

Step 5: when to ask

Pages that ask for notification permission the moment they load are the reason browsers now play these prompts down, and many people refuse them on reflex. The prompt makes sense when the user has just asked for something that needs it, such as pressing "Alert me before my bus leaves". Call notify from that button's click handler, not on page load.

The full solution

The full solution uses four stand-in Notifications: fresh and allowed, fresh and refused, already denied, and already granted. Its checks confirm a fresh browser starts at 'default', asking and being allowed sends one notification with the right title and body, being refused sends nothing and says so, an already-denied browser isn't asked again and re-asking returns 'denied', an already-granted browser sends straight away, and creating a notification without permission throws. Press Run. The live demo uses the real API, which a sandboxed frame usually blocks, so you will most likely see the refused path.

Live, in a real browser. Click it. Sandboxed to allow-scripts only, so it cannot reach this page.

The answer

const out = el('pre', { id: 'out' });
document.body.appendChild(out);

/* All three states handled, and the order matters: check 'denied' BEFORE asking,
   because asking again after a refusal is pointless and the answer is 'denied'
   without any prompt. */
async function notify(Notification, title, body) {
  if (Notification.permission === 'denied') {
    return { state: 'denied', message: 'Permission was refused earlier. The browser will not ask again.' };
  }

  if (Notification.permission === 'default') {
    const answer = await Notification.requestPermission();
    if (answer !== 'granted') {
      return { state: answer, message: `Not granted: "${answer}". Nothing sent.` };
    }
  }

  try {
    new Notification(title, { body });        // throws without permission
    return { state: 'sent', message: 'Sent.' };
  } catch (error) {
    return { state: 'error', message: `Could not send: ${error.name}` };
  }
}

const fresh = makeNotification('default', 'granted');
const willRefuse = makeNotification('default', 'denied');
const alreadyDenied = makeNotification('denied', 'granted');
const alreadyGranted = makeNotification('granted', 'granted');

console.log('a fresh browser, permission is:', fresh.permission);
const first = await notify(fresh, 'Bus departing', 'Ojota to Abuja, 14 seats left');
console.log('after asking and being allowed :', first, '| now:', fresh.permission);
console.log('what was shown                 :', fresh.shown);

const refusedNow = await notify(willRefuse, 'Bus departing', 'body');
console.log('asked and refused              :', refusedNow);

const denied = await notify(alreadyDenied, 'Bus departing', 'body');
console.log('already denied                 :', denied);
console.log('re-asking after a refusal gives :', await alreadyDenied.requestPermission(), '<- no prompt');

const straight = await notify(alreadyGranted, 'Already allowed', 'no prompt needed');
console.log('already granted                :', straight);

// Constructing one without permission throws.
const tooEarly = makeNotification('default', 'granted');
let threw = null;
try { new tooEarly('too early'); } catch (e) { threw = e.constructor.name; }
console.log('constructing before granting   :', threw);

Output


      
16 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 16 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

16 checks

test('permission starts as default', makeNotification('default').permission, 'default');
test('asking and being allowed sends it', first.state, 'sent');
test('and the permission is now granted', fresh.permission, 'granted');
test('the notification carries its title', fresh.shown[0].title, 'Bus departing');
test('and its body', fresh.shown[0].body, 'Ojota to Abuja, 14 seats left');
test('exactly one was shown', fresh.shown.length, 1);
test('being refused when asked sends nothing', refusedNow.state, 'denied');
test('and says so', refusedNow.message.includes('Nothing sent'), true);
test('an already-denied browser is not asked again', denied.state, 'denied');
test('with a message explaining it is final', denied.message.includes('will not ask again'), true);
test('re-asking after a refusal returns denied without prompting', await alreadyDenied.requestPermission(), 'denied');
test('and it stays denied', alreadyDenied.permission, 'denied');
test('an already-granted browser sends straight away', straight.state, 'sent');
test('constructing without permission throws', threw, 'TypeError');
test('so the check has to come first', tooEarly.shown.length, 0);
test('the three states are the only ones', ['default', 'granted', 'denied'].includes(fresh.permission), true);

Adapted: a stand-in Notification, so all four paths — fresh and allowed, fresh and refused, already denied, already granted — are asserted. A sandboxed frame usually cannot show real notifications, so the demo will most likely take the refused path, which is the one worth seeing anyway.

Checking 'denied' before calling requestPermission() is the ordering that matters. A browser never re-prompts after a refusal: the promise resolves to 'denied' immediately with no dialog, so asking again just produces a silent no. The assertion confirms that. Tell the user it was refused rather than appearing to try.

Constructing a Notification without permission throws a TypeError, which the assertions check, so the permission test cannot be skipped.

Worth saying plainly: asking for notification permission the moment a page loads is the reason browsers now suppress these prompts, and Chrome and Firefox both hide repeat requests. Ask after the user does something that implies they want to be told — subscribing to a departure alert, say — not on arrival.

Common mistakes

  • Asking again after a refusal. The browser won't show the prompt. Check for 'denied' first and explain.
  • Creating a notification before checking permission. Nothing appears. Check, and ask if needed, first.
  • Asking on page load. Users refuse a prompt they don't understand, and the refusal is permanent.

Try it yourself

  1. Add a "What is the current state?" button that shows Notification.permission on the page.
  2. Make notify return { state: 'unsupported' } when typeof Notification is 'undefined'.
  3. Close the notification by itself after 5 seconds: keep the object new Notification returns, and call its close() method from a setTimeout.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.