服务器端使用PHP的浏览器通知

Joe*_*mes 0 javascript php push-notification

我可以使用PHP从服务器向订阅用户发送浏览器通知吗?我今天看到了这个教程,但这只能从客户端开始.我知道有像pushcrew这样的服务,但我想用PHP和JavaScript开发自己的服务.

我的实际要求是要求用户确认是否可以使用此代码向他们发送通知,

if (Notification.permission !== "granted")
{
   Notification.requestPermission();
}
Run Code Online (Sandbox Code Playgroud)

然后在我的网站上发布新文章时显示通知.

注意:浏览器支持无关紧要.

Fab*_*her 5

您必须在客户端触发这些通知,因此您需要将它们从PHP服务器提供给您的JavaScript:

  • 每隔x秒执行一次ajax轮询,例如使用jQuery ajax函数,并在服务器返回一个时显示一条消息
  • 通过WebSockets推送消息,例如使用Ratchet

即使用户没有打开网站并且最近的Firefox 44支持,Web Push也允许您推送通知.它在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();
}
Run Code Online (Sandbox Code Playgroud)

如果有消息,JSON服务器在"test.json"中回答:

{
    "notify": true,
    "title": "Hey there!",
    "desc": "This is a new message for you",
    "url": "http://stackoverflow.com"
}
Run Code Online (Sandbox Code Playgroud)

JSON服务器在"test.json"中回答不显示消息:

{
    "notify": false
}
Run Code Online (Sandbox Code Playgroud)

  • 你完全错了!浏览器通知不同。他们首先征求您的同意,然后才会开始显示通知。根本没有垃圾邮件。不同的域需要不同的权限。它不需要网页处于活动状态。如果您的浏览器已打开,它将显示通知。请参阅此链接 - https://developer.mozilla.org/en/docs/Web/API/notification (3认同)
  • 当用户在我的页面上处于活动状态时,您的方法用于自定义通知。但是我的要求是即使用户在我的网站上不活跃,也要使用浏览器通知。 (2认同)
  • "Notifications API允许网页控制向最终用户显示系统通知 - 这些是在顶级浏览上下文视口之外,因此即使用户已切换标签或移动到其他应用程序,也可以显示." https://developer.mozilla.org/en-US/docs/Web/API/Notifications_API (2认同)