Notification Web API

Notification Web API - www.coisadeprogramador.com.br example

by William Sena

JavaScript

function isNotificationEnabled() {
  if(!window.Notification) {
    console.log('Oooh no! Your browser is too old!');
    return false;
  }

  return true;
}

function RequestPermission(callback){
  callback = callback || function(status) {
    console.log('Status da permissĂŁo: ' + status);
    callback(status === "granted");
  };
  
  Notification.requestPermission(callback);
}

function SendNotification(message, callback){
   if(!isNotificationEnabled()){
   	return;
   }
   
   if(Notification.permission === 'default') {
      RequestPermission();
      return;
   }
   
   callback = callback = {};
   
   if(typeof message !== 'object'|| !message.body || !message.title){
     throw new Error('Invalid message!');
     return;
   }
   
   var notification = new Notification(message.title, {
     body: message.body,
     tag: message.tag,
     icon: message.icon
    });
    
    notification.onshow = callback.show || function show() {
     console.log('OnShow: Yeah! Notification success');
    };
    
    notification.onclick = callback.click || function click() {
     console.log('OnClick: Notification clicked');
    };
    
    notification.onclose = callback.close || function close() {
     console.log('OnClose: Notification closed');
    };
    
    notification.onerror = callback.error ||  function error() {
     console.log('OnError: Unexpected error');
    };
}

(function(){
  if(!isNotificationEnabled()){
    return;
  }
  
  SendNotification({ 
    title: 'Coisa de Programador', 
    body: 'Oh Yeah! Good news.',
    icon: 'https://thenypost.files.wordpress.com/2016/02/deadpool_poster2a.jpg?quality=100&strip=all&strip=all'
  }, {
    success: function(){
      console.log('Good news!');
    },
    error: function(){
      console.log('Bad news!');
    }
  });

})();