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.过多的使用可能会影响页面性能。

相关推荐
北城笑笑3 小时前
Vue 112 ,下篇:前端 dist 还原成 Vue3 + Vite 项目( krpano 全景接入与页面适配实战,Vue2 → Vue3 )
前端·javascript·vue.js·3d·前端框架·vue·webgl
我叫黑大帅4 小时前
搜“张三”把备注也带出来了?不用加高级筛选,如何让一个搜索框实现「选项直达」!
前端·javascript·面试
如夏倾城6 小时前
WAF (Web Application Firewall,Web应用防火墙)
前端·网络·安全·web安全·web app
图扑可视化7 小时前
基于图扑软件智慧制硅厂 Web SCADA 开发实践
前端·三维可视化·scada·hmi·组态软件
前端fighter7 小时前
2026年前端面试题总结(pdf版)
前端·pdf
谢小飞7 小时前
运维加了个参数,我们的网页挂掉了
前端·浏览器
CoderYanger8 小时前
Java EE 进阶:12.Spring AOP(第二弹)
java·前端·数据库·spring boot·spring·java-ee·mybatis
用户693717500138411 小时前
大模型蒸馏到底在蒸什么?一篇文章搞懂知识蒸馏概念
前端·后端·github
徐小夕11 小时前
实测 10 个前端 UI 生成开源 Skill|AI 输出直达上线标准
前端·vue.js·github
tong_li11 小时前
给娃做个 AI 陪写作业助手:LangChain4j 入门(八):AI 知道这字哪课学的(SQLite 结构化查询入门)
前端·langchain