HTML5 桌面通知

71 阅读1分钟
 <script>
    const notification = window.Notification||window.mozNotification||window.webkitNotification
    if (notification) {
      // 使用箭头函数变更this指向
      notification.requestPermission(result => {
        // result 为granted(允许) denied(拒绝)
        // denied表示需要授权浏览器通知, 设置如下图1
        const tag = 'tag' + new Date().getTime()
        const notify = new notification(
          '标题', // title标题
          {
            dir: 'auto', // 文字的方向, 它的值可以是 auto(自动), ltr(从左到右), rtl(从右到左)
            lang: 'zh-CN', // 指定通知中所使用的语言
            body: 'body字符串', // 通知中额外显示的字符串
            tag: tag,  // 赋予通知一个ID, 以便在必要的时候对通知进行刷新 替换或移除
            requireInteraction: false, //通知保持有效不自动关闭,默认为false
            // icon: './favicon.ico' // 将被用于显示通知的图标
          })
        notify.onshow = () => {
          // 通知弹框显示时
          console.log('show methods')
        }
        notify.onclick = () => {
          // 点击通知弹框
          console.info('click methods')
        }
        notify.onerror = () => {
          console.error('error methods')
        }
        notify.onclose = () => {
          console.info('close methods')
        }
      })
    } else {
      console.warn('浏览器不支持通知!')
    }
  </script>

图1:

image.png