javascript web调用Notification提示
·
1 先检查一下电脑系统的消息 是否开启提示了(非常重要)
踩坑ing 一直有消息通知的声音 但就是看不见弹窗所以一定要开
2 复制代码
- 调用新增消息提示
- Notification.permission === “granted” 允许web页接收消息
- 如果Notification.permission !== “granted” 说明没有同意权限 就要执行Notification.requestPermission()申请权限
/**
* openNotification 新增消息提示
* @param {string} TITLE 标题
* @param {string} MSG 信息
* @param {string} ICON 图标 可以使用import的图标
* @param {function} CALLBACK 消息点击事件
*/
function openNotification(TITLE = '', MSG = '', ICON = '', CALLBACK = null) {
if (Notification.permission === "granted") {
notifyCallback()
} else {
Notification.requestPermission().then((status) => {
if (status === "granted") {
notifyCallback()
}
})
}
function notifyCallback() {
const instance = new Notification(TITLE, { body: MSG, icon: ICON });
instance.onclick = () =>{
CALLBACK && CALLBACK()
window.focus();
}
}
}
3 示例 这里有一些腾讯im的代码 可以忽略
这里如果在浏览器tab没有在当前页面时候 接收到消息就触发系统通知 如果在当前tab就不触发
mounted() {
const that = this;
TUILogin.chat.on('onMessageReceived', function (message) {
if (document.visibilityState === 'hidden') {
const text = message?.data[0]?.payload?.text || '';
const user = message?.data[0]?.from?.replace('user', '') || '';
const callback = () => {
const timer = setTimeout(() => {
that.$broadcast.fire('txImCurrentUser', user);
that.$router.push({ path: '/tuikit' });
clearTimeout(timer);
}, 1000);
}
openNotification('新消息', text, 'icon地址', callback);
}
});
}
更多推荐

所有评论(0)