我可以使用 PHP 从服务器向订阅用户发送浏览器通知吗?我今天看到了本教程,但它只能从客户端工作。我知道有像pushcrew这样的服务,但我想使用PHP和JavaScript开发自己的服务。
我的实际要求是要求用户确认我是否可以使用此代码向他们发送通知,
if (Notification.permission !== "granted")
{
Notification.requestPermission();
}
然后在我在我的网站上发布新文章时显示通知。
注意:浏览器支持无关紧要。
你必须在客户端触发这些通知,所以你需要将它们从PHP服务器获取到你的JavaScript:
- 每x秒执行一次Ajax轮询,例如使用jQuery ajax函数,如果服务器返回一条消息,则显示一条消息
- 通过 WebSocket 推送消息,例如使用 Ratchet
Web 推送允许您推送通知,即使用户没有打开网站,并且受最近的 Firefox 44 支持。它在Chrome中部分受支持。有关详细信息,请查看Mozilla Hacks博客。
轮询示例
JavaScript jQuery 部分:
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 服务器在"test.json"中回答是否有消息:
{
"notify": true,
"title": "Hey there!",
"desc": "This is a new message for you",
"url": "http://stackoverflow.com"
}
JSON 服务器在"test.json"中回答不显示消息:
{
"notify": false
}