diff --git a/src/chat.js b/src/chat.js index 87e4904..9b167a6 100644 --- a/src/chat.js +++ b/src/chat.js @@ -128,6 +128,31 @@ export default class Chat { }, 'style')) this.从本地载入消息() this.挂载全局快捷键() + + // 如果未询问用户是否允许通知,则询问用户是否允许通知 + if (Notification.permission === 'default') { + Notification.requestPermission() + } + } + async 通知栏消息(data) { + console.log('通知栏消息', data) + const { name, text, time, type } = data + const icon = 'https://webrtc.satori.love/favicon.ico' + // 如果页面可见或且浏览器不在前台运行, 则发送通知 + if (document.visibilityState === 'visible') return console.log('页面可见') + // 如果用户不允许通知,则不发送通知 + if (Notification.permission !== 'granted') return console.log('用户不允许通知') + // 如果未询问用户是否允许通知,则询问用户是否允许通知 + if (Notification.permission === 'default') { + await Notification.requestPermission() + } + if (Notification.permission === 'granted') { + const notification = new Notification(name, { body: text, icon }) + notification.onclick = () => { + window.focus() + notification.close() + } + } } async 挂载全局快捷键() { document.addEventListener('keydown', event => { @@ -346,5 +371,6 @@ export default class Chat { console.log('收到消息', data) this.添加元素(data) this.存储消息(data) + this.通知栏消息(data) } } \ No newline at end of file