天天看點

HTML5 桌面通知

第1步:檢查通知API的支援

if (window.webkitNotifications) {
  console.log("浏覽器支援桌面通知");
}
else {
  console.log("浏覽器不支援桌面通知 建議使用Chrome");
}
           

第2步:擷取權限

document.querySelector('#show_button').addEventListener('click', function() {
  if (window.webkitNotifications.checkPermission() == 0) { // 0 表示允許
    // 建立通知
    window.webkitNotifications.createNotification(
        'icon.png', 'Notification Title', 'Notification content...');
  } else {
    window.webkitNotifications.requestPermission();
  }
}, false);
           

第3步:添加監聽器&方法

document.querySelector('#show_button').addEventListener('click', function() {
  if (window.webkitNotifications.checkPermission() == 0) { // 0 表示允許
    // 建立通知 并且綁定通知的各種事件的處理。
    notification_test = window.webkitNotifications.createNotification(
      'icon.png', 'Notification Title', 'Notification content...');
    notification_test.ondisplay = function() { ... do something ... };
    notification_test.onclose = function() { ... do something else ... };
    notification_test.show();
  } else {
    window.webkitNotifications.requestPermission();
  }
}, false);