天天看点

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);