js实现网页在桌面通知

这段代码展示了如何在浏览器中实现桌面通知功能。如果浏览器支持`Notification`接口,它会根据用户权限设置显示通知,并允许在通知上绑定自定义事件处理。在用户点击通知时,会关闭通知并使窗口获取焦点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

	function doNotify(title, options = {}, events = {}) {
      const notification = new Notification(title, options);
      for (let event in events) {
        notification[event] = events[event];
      }
    }

    function notify(title, options = {}, events = {}) {
      if (!("Notification" in window)) {
        return console.error("This browser does not support desktop notification");
      }
      else if (Notification.permission === "granted") {
        doNotify(title, options, events);
      } else if (Notification.permission !== "denied") {
        Notification.requestPermission().then(function (permission) {
          if (permission === "granted") {
            doNotify(title, options, events);
          }
        });
      }
    }


    notify("标题", {
      icon: "图片地址",
      body: "通知内容",
    }, {
      onclick(ev) {
        ev.target.close();
        window.focus();
      }
    })

在‘前端瓶子君‘公众号中学习所得,做以记录

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值