1. 程式人生 > >HTML5之Notification簡單使用

HTML5之Notification簡單使用

element per html close style source lose app javascrip

var webNotification = {
  init: function() {
    if(!this.isSupport()) {
      console.log(‘不支持通知‘);
      return;
    }
    this.initElement();
    this.initPermission();
  },
  isSupport: function() {
    return !!window.Notification;
  },
  element: null,
  isPermission: false,
  initElement: function
() { var element = document.createElement(‘button‘); element.type = ‘button‘; element.style = ‘position: absolute;top: -100px;‘; element.onclick = function() { Notification.requestPermission(function(result) { console.log(‘result:‘ + result); if(result === ‘granted‘
) { this.isPermission = true; } else { this.isPermission = false; } }.bind(this)); }.bind(this); document.body.appendChild(element); this.element = element; }, initPermission: function() { this.element.click(); }, notify: function(title,
options, clickCallback, closeCallback) { var notification = new Notification(title, options); notification.onclick = clickCallback; notification.onclose = closeCallback; return notification; } };

初始化

webNotification.init();

測試

webNotification.notify(‘我是標題‘, {
  body: ‘我是通知內容‘,
  icon: ‘/favicon.ico‘,
}, function() {
  alert(‘我點擊了通知‘);
}, function() {
  alert(‘我關閉了通知‘);
});

HTML5之Notification簡單使用