vue 浏览器通知
noticeRemind(target) {
const notificationInstanceArr = []
// const notificationAudio = new Audio('https://img-fe.tengzhihh.com/audio/c58fb135c2546f.mp3')
const handleMessageFocus = (target) => {
// 可以在这里 根据新消息target,处理展示具体会话逻辑
// 展示原有页面
window.focus()
// 删除点击的会话通知
for (let i = 0; i < notificationInstanceArr.length; i++) {
if (notificationInstanceArr[i].task_id === target.task_id) {
notificationInstanceArr[i].instance.close()
notificationInstanceArr.splice(i, 1)
i--
}
}
}
if (!('Notification' in window)) {
console.log('浏览器不支持消息通知')
return
}
// 创建配置项
const options = {
body: '您有新的未读消息', // 展示内容
silent: false, // 是否静音
lang: 'ZH',
sticky: true, // 是否粘性展示,不轻易被清理
// renotify: true, // 弹窗内容更新,是否重新通知,需与tag搭配使用
requireInteraction: true // 是否保持,不自动关闭
}
// 检查权限是否已获取 已获取为granted
if (Notification.permission !== 'granted') {
// 未允许权限,则申请权限
Notification.requestPermission(function(status) {
if (status === 'granted') {
// 创建提醒
const notification = new Notification(target.task_content, options)
// 设置点击事件
notification.onclick = function() {
handleMessageFocus(target)
}
// 存储通知实例,保留最新三个
if (notificationInstanceArr.length === 3) {
const instance = notificationInstanceArr.shift()?.instance
instance?.close()
}
notificationInstanceArr.push({
task_id: target.task_id,
instance: notification
})
// 播放通知音频
// notificationAudio?.play()
}
})
} else {
// 已有权限,重复操作即可
const notification = new Notification(target.task_content, options)
notification.onclick = function() {
handleMessageFocus(target)
}
if (notificationInstanceArr.length === 3) {
const instance = notificationInstanceArr.shift()?.instance
instance?.close()
}
notificationInstanceArr.push({
task_id: target.task_id,
instance: notification
})
// notificationAudio?.play()
}
}
浙公网安备 33010602011771号