JavaScript ile Tarayıcı Bildirimi Göndermek

JavaScript Browser Notification örneği

easyNotify.js oluşturun ve içerisine;

(function($) {

  $.fn.easyNotify = function(options) {
  
    var settings = $.extend({
      title: "Notification",
      options: {
        body: "",
        icon: "",
        lang: 'pt-BR',
        onClose: "",
        onClick: "",
        onError: ""
      }
    }, options);

    this.init = function() {
        var notify = this;
      if (!("Notification" in window)) {
        alert("This browser does not support desktop notification");
      } else if (Notification.permission === "granted") {

        var notification = new Notification(settings.title, settings.options);
        
        notification.onclose = function() {
            if (typeof settings.options.onClose == 'function') { 
                settings.options.onClose();
            }
        };

        notification.onclick = function(){
            if (typeof settings.options.onClick == 'function') { 
                settings.options.onClick();
            }
        };

        notification.onerror  = function(){
            if (typeof settings.options.onError  == 'function') { 
                settings.options.onError();
            }
        };

      } else if (Notification.permission !== 'denied') {
        Notification.requestPermission(function(permission) {
          if (permission === "granted") {
            notify.init();
          }

        });
      }

    };

    this.init();
    return this;
  };

}(jQuery));

Sitenizde ilgili kısımda dosyayı çağırın

<script src="js/easyNotify.js"></script>
< script >

function showNotification() {
	if(window.Notification) {
		Notification.requestPermission(function(status) { 
			
			$.ajax({
				type: "GET",
				url: "notification.json",
				dataType: 'json',
				contentType: "application/json; charset=utf-8",
				data: "{}",
				success: function(data){
					var options = {
					title: $("#title").val(),
					options: {
					  body: data[0].body,
					  icon: data[0].icon,
					  lang: 'en-US',
					  onClick: function(){
						  window.open(data[0].link);
					  }
					}
				  };
				  $("#easyNotify").easyNotify(options);
				}
			}); 
			
		});
	}else{
		//alert('Your browser doesn\'t support notifications.');
	}
}


setInterval(function() {
    showNotification();
	//1 dakikada bir bildirim gönder
}, 60000);


notification.json için

[ 
  {
	"title": "Hey there!",
	"body": "This is a new message for you",
	"icon": "https://unsplash.it/600/600?image=787",
	"link": "http://stackoverflow.com"
  },
  {
	"title": "Hey there!",
	"body": "This is a new message for you",
	"icon": "https://unsplash.it/600/600?image=777",
	"link": "http://stackoverflow.com"
  }
]
Bu makaleyi paylaşın:

3 Comments

Bir yorum bırakın