[html5] (Notification) 桌面通知

前几天要做一个桌面通知的功能,翻查以前做的笔记,发现 webkitNotifications这个已经不能用了,baidu了下,基本都是介绍webkitNotifications的,后来在SOF上找到答案,现在chrome支持的是Notification,估计是W3C标准化了。api也变了,mark之。

Notification

Properties

《[html5] (Notification) 桌面通知》

title: “别动神仙说: “
body: “这里是body”
icon: “http://q4.qlogo.cn/g?b=qq&k=icUjVAN5Ja7BCDQ1ICl8Svw&s=40
tag: “1” // 通知框ID,相同id可替换,而不是出现新的通知框
lang: “” // 语言
dir: “auto” // 文字方向

new Notification('别动神仙说:', {
    body: '这里是body',
    icon: 'http://q4.qlogo.cn/g?b=qq&k=icUjVAN5Ja7BCDQ1ICl8Svw&s=40',
    tag: 1
});

onshow: null // 显示通知框时调用
onclick: null // 点击通知框时调用
onclose: null // 点击通知框关闭按钮时调用
onerror: null

例如实现通知弹出一段时间后自动关闭

var notification = new Notification('标题');
notification.onshow = function () {
    setTimeout(function () {
        notification.close();
    }, 3000);
}

Notification.permission
有三种状态

  • default:未设置过为这个状态,通过Notification.requestPermission()可以询问用户是否允许通知
  • granted:用户点击允许后的状态
  • denied: 用户点击拒绝后的状态,通知框不可用

Methods

Notification.requestPermission()
《[html5] (Notification) 桌面通知》
一般在Notification.permission === ‘default’时,用户通过点击等操作调用

document.onclick = function() {
    Notification.requestPermission()
}

使用回调

Notification.requestPermission(function (permission) {
    // 可在确认后直接弹出
    if (permission === 'granted') {
        var notification = new Notification('弹窗');
    }
});

Notification.close()
通知框关闭

function notify() {
    if (!("Notification" in window)) {
        alert("This browser does not support desktop notification");
        return;
    } 

    if (Notification.permission === "granted") {
        var notification = new Notification("Hi there!");
    } 
    else if (Notification.permission === 'default') {
        Notification.requestPermission(function (permission) {
            if (permission === "granted") {
                var notification = new Notification("Hi there!");
            }
        });
    }
}

References:

https://developer.mozilla.org/en-US/docs/Web/API/Notification.tag

    原文作者:vczhan
    原文地址: https://segmentfault.com/a/1190000000663792
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞