vue 在web网页中实现浏览器最小化时电脑端的弹窗通知

89 阅读1分钟

前言:1、通知弹窗只有在页面打开的时候会弹出。2、需要浏览器支持通知功能,并且需要用户授权通知

// 检查浏览器是否支持通知功能,并让用户授权弹窗通知
mounted() {
    // 检查浏览器是否支持通知功能
    if ('Notification' in window) {
      console.log('浏览器支持通知功能');
      // 请求通知权限
      Notification.requestPermission().then(permission => {
        if (permission === 'granted') {
          console.log('通知权限已授予');
        } else {
          console.log('通知权限未被授予');
        }
      });
    } else {
      console.log('浏览器不支持通知功能');
    }
},
methods: {
    // 电脑弹窗
    showNotification(info) {
     //document.hidden 检测浏览器是否最小化
      if (document.hidden) {
          if ('Notification' in window && Notification.permission === 'granted') {
            const notification = new Notification(`来自${info.username}的新消息`, {
              body: `${info.picurl ? '[图片]' : info.content}`,
              icon: require('@/assets/logo.png'), // 可选:通知图标
              requireInteraction: true // 防止通知自动关闭,false:几秒后自动关闭
            });

            // 点击通知时跳转到指定页面
            notification.onclick = function () {
              window.location.href = 'http://localhost:8080/#/chat'; // 替换为你的目标页面
              notification.close(); // 点击后关闭通知
            };
          } else {
            console.log('通知权限未开启');
          }
      }
    },
}

效果图: image.png

image.png