[html5] (Notification) 桌面通知

前幾天要作一個桌面通知的功能,翻查之前作的筆記,發現 webkitNotifications這個已經不能用了,baidu了下,基本都是介紹webkitNotifications的,後來在SOF上找到答案,如今chrome支持的是Notification,估計是W3C標準化了。api也變了,mark之。javascript


Notification

Properties

dialog of Notification

title: "別動神仙說: "
body: "這裏是body"
icon: "http://q4.qlogo.cn/g?b=qq&k=icUjVAN5Ja7BCDQ1ICl8Svw&s=40"
tag: "1" // 通知框ID,相同id可替換,而不是出現新的通知框
lang: "" // 語言
dir: "auto" // 文字方向java

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: nullweb

例如實現通知彈出一段時間後自動關閉chrome

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

Notification.permission
有三種狀態segmentfault

  • default:未設置過爲這個狀態,經過Notification.requestPermission()能夠詢問用戶是否容許通知
  • granted:用戶點擊容許後的狀態
  • denied: 用戶點擊拒絕後的狀態,通知框不可用

Methods

Notification.requestPermission()
popover requesting for the user’s permission
通常在Notification.permission === 'default'時,用戶經過點擊等操做調用api

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

使用回調spa

Notification.requestPermission(function (permission) {
    // 可在確認後直接彈出
    if (permission === 'granted') {
        var notification = new Notification('彈窗');
    }
});

Notification.close()
通知框關閉code

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.tagip

相關文章
相關標籤/搜索