← 中文资源

简体中文版本

通知权限请求流程

先用 Notification.permission 免弹窗读当前状态,已拒绝直接走降级文案;再在用户手势里调 requestPermission,拿到 granted 才发通知。

阅读英文原文

实现说明

全部逻辑都在函数 permissionFlow中。 异步部分依次 await 结果,顺序可预测。

使用要点

  • 守卫 state === 'granted' 满足时靠提前的 return 短路流程。
  • 直接运行文件,输出会带上标签,比如 current permission:、requestPermission resolved with:、notification closed by user——输出的每一行都能指回产生它的那次调用。

常见问题

运行前要先安装什么?

什么都不用额外装——运行时自带了代码所需的一切。 文件在加载时定义 permissionFlow。

入口签名:async function permissionFlow()

核心语句

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

代码示例

// 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));