首先要获取权限,如果返回 granted 为获取通知权限成功,如果为 denied 获取通知失败,注⚠️ :一旦拒绝,就无法通过编程方式挽回,因为不可能再触发授权提示。
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title></head><body></body></html><script>Notification.requestPermission().then((res) => {if (res === 'granted') {console.log('获取权限');let n = new Notification('系统消息', {body: 'body 内容',image: "https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=1200969649,1714025549&fm=26&gp=0.jpg",vibrate: true, // 震动})// 发送消息后的通知n.onshow = function () {console.log('通知显示');}// 通知被点击时触发n.onclick = function(){console.log('通知被点击');}// 通知消失或被取消n.onclose = function(){console.log('通知被关闭');}// 发送错误阻止通知显示时触发n.onerror = function(){console.log('发生错误');}} else if (res === 'denied') {console.log('没有权限');}})</script>
