Reputation: 1345
Can I send browser notifications from server to subscribed users using PHP? I saw this tutorial today, but that work only from client side. I know there are services like pushcrew, but I want to develop my own using PHP and JavaScript.
My actual requirement is asking users to confirm if I can send them notifications using this code,
if (Notification.permission !== "granted")
{
Notification.requestPermission();
}
then show notifications when I publish new article in my website.
NB: Browser support doesn't matter.
Upvotes: 4
Views: 21491
Reputation: 1929
You have to trigger these notifications on the client side, so you need to get them from the PHP server to your JavaScript:
Web Push allows you to push notification even if the user didn’t have the site open and is supported by the recent Firefox 44. It is partially supported in Chrome. For details check out the Mozilla Hacks blog.
Example with polling
JavaScript jQuery part:
function doPoll() {
// Get the JSON
$.ajax({ url: 'test.json', success: function(data){
if(data.notify) {
// Yeah, there is a new notification! Show it to the user
var notification = new Notification(data.title, {
icon:'https://lh3.googleusercontent.com/-aCFiK4baXX4/VjmGJojsQ_I/AAAAAAAANJg/h-sLVX1M5zA/s48-Ic42/eggsmall.png',
body: data.desc,
});
notification.onclick = function () {
window.open(data.url);
};
}
// Retry after a second
setTimeout(doPoll,1000);
}, dataType: "json"});
}
if (Notification.permission !== "granted")
{
// Request permission to send browser notifications
Notification.requestPermission().then(function(result) {
if (result === 'default') {
// Permission granted
doPoll();
}
});
} else {
doPoll();
}
JSON server answer in "test.json" if there is a message:
{
"notify": true,
"title": "Hey there!",
"desc": "This is a new message for you",
"url": "http://stackoverflow.com"
}
JSON server answer in "test.json" to not show a message:
{
"notify": false
}
Upvotes: 6