Notification Permission Request Flow

Read Notification.permission without prompting, then call requestPermission inside a user gesture and branch on the resolved decision before showing a note.

JavascriptSecurity Boundaries

Code

javascriptsnippet
20 lines
// Notification.permission exposes the current state without any prompt
const state = Notification.permission;
console.log('current permission:', state);

// requestPermission must run inside a user gesture and resolves
// with the final decision
async function permissionFlow() {
  if (state === 'granted') return 'already granted';
  if (state === 'denied') return 'blocked: user must clear site settings';
  const decision = await Notification.requestPermission();
  console.log('requestPermission resolved with:', decision);
  if (decision === 'granted') {
    const note = new Notification('Deploy finished', { body: 'build 42 is live' });
    note.addEventListener('close', () => console.log('notification closed by user'));
    return 'granted: notification shown';
  }
  return 'decision: ' + decision;
}

permissionFlow().then((message) => console.log(message));

How it works

Everything happens inside the function permissionFlow.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

Points of care

  • The guard state === 'granted' cuts off everything after it by throwing an early return when its condition holds.

Using it

Entry signature: async function permissionFlow()

Output lines are prefixed (current permission:, requestPermission resolved with:, notification closed by user), making each step’s effect easy to spot.

Key statements

if (state === 'denied') return 'blocked: user must clear site settings';
const decision = await Notification.requestPermission();
if (state === 'granted') return 'already granted';

Interactive Tools for This Topic

FAQ

What has to be installed first?
Nothing — the runtime itself provides everything the code touches. The file defines `permissionFlow` at load time.