Chrome浏览器使用Notification通知消息推送

代码如下

<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>

  <body>
    <script>
      function createNotify(title, options) {
        var PERMISSON_GRANTED = "granted";
        var PERMISSON_DENIED = "denied";
        var PERMISSON_DEFAULT = "default";
        
        // 如果用户已经允许,直接显示消息,如果不允许则提示用户授权
        if (Notification.permission === PERMISSON_GRANTED) {
          notify(title, options);
        } else {
          Notification.requestPermission(function (res) {
            if (res === PERMISSON_GRANTED) {
              notify(title, options);
            }
          });
        }

        // 显示提示消息
        function notify($title, $options) {
          var notification = new Notification($title, $options);
          console.log(notification);
          notification.onshow = function (event) {
            console.log("show : ", event);
          };
          notification.onclose = function (event) {
            console.log("close : ", event);
          };
          notification.onclick = function (event) {
            console.log("click : ", event);
            // 当点击事件触发,打开指定的url
            window.open(event.target.data)
            notification.close();
          };
        }
      }

      createNotify("新的消息", {
        body: "你有一个奖品待领取",
        icon: "https://www.baidu.com/favicon.ico",
        data: "https://www.baidu.com/"
      });

      /* 依次打印
       * show:   Event Object(事件对象),事件的type为"show"
       * click:  Event Object(事件对象),事件的type为"click"。点击消息后消息被关闭,跳到close事件。
       * close:  Event Object(事件对象),事件的type为"close"
       */
    </script>
  </body>
</html>

各浏览器的支持不是很统一
https://www.caniuse.com/?search=Notification
在这里插入图片描述

文件直接打开没有效果,需要由后台服务提供页面

参考
Notification 浏览器的消息推送

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值