Web Notifications API-让网页也能像QQ一样实现消息通知

一.什么是Web Notifications API

Web Notifications API允许网页或者是应用程序以系统级别发送在页面外部显示的通知,这样就可以实现即时应用程序在后台或者是空闲状态,Web应用程序也会向用户发送信息。

二.Notification的状态

1.denied(拒绝)------不允许发送通知

2.granted(同意)------允许发送通知

3.default(默认状态)------根据浏览器来决定,一般是询问浏览器,来请求获取发送通知的权限

三.场景实现步骤

1.检查浏览器是否支持

2.首先请求权限,在应用程序可以发送通知之前,需要用户授予应用程序发生通知的权限

3.创建并显示通知

具体实现代码

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Notification Example</title>
<script>
// 当页面加载时执行
document.addEventListener('DOMContentLoaded', function() {
  // 检查浏览器是否支持Notification API
  if (!("Notification" in window)) {
    alert("This browser does not support desktop notification");
  }
  // 检查用户是否已经授予权限
  else if (Notification.permission === "granted") {
    // 如果已经授权,可以直接显示通知
    showNotification();
  }

  // 如果用户尚未做出选择或默认为'default',则请求权限
  else if (Notification.permission !== "denied") {
    Notification.requestPermission().then(function(permission) {
      // 一旦用户响应,可以显示通知
      if (permission === "granted") {
        showNotification();
      }
    });
  }

  // 显示通知的函数
  function showNotification() {
    var notification = new Notification("Hello", {
      body: "This is a notification message!",
      icon: 'icon.png' // 路径到图标文件
    });

    // 可以添加事件监听器来处理用户交互
    notification.onclick = function() {
      // 这里可以打开新窗口或跳转到特定页面
      window.open('https://www.example.com', '_blank');
    };
  }
});
</script>
</head>
<body>
<h1>Web Notifications API Example</h1>
<p>Check the top-right corner for the notification!</p>
</body>
</html>

四.优缺点:

优点:1.可以定制通知的外观和行为

2.不需要用户授权

3.可以应用到现有的网页设计中

缺点:1.需要适配移动端设备

2.过多的使用可能会影响页面性能。

相关推荐
小奋斗16 小时前
面试官:[1] == '1'和[1] == 1结果是什么?
前端·面试
萌萌哒草头将军16 小时前
尤雨溪宣布 oxfmt 即将发布!比 Prettier 快45倍 🚀🚀🚀
前端·webpack·vite
weixin_4050233716 小时前
webpack 学习
前端·学习·webpack
云中雾丽16 小时前
flutter中 Future 详细介绍
前端
求知呀16 小时前
服务器状态管理 Vue Query
前端
在下Z.16 小时前
前端基础--css(1)
前端·css
常在士心16 小时前
Flutter项目支持鸿蒙环境
前端
重生之我要当java大帝16 小时前
java微服务-尚医通-管理平台前端搭建-医院设置管理-4
java·开发语言·前端
用户595619575452316 小时前
Vue-i18n踩坑记录
前端
WindrunnerMax16 小时前
从零实现富文本编辑器#8-浏览器输入模式的非受控DOM行为
前端·前端框架·github