Joe*_*mes 0 javascript php push-notification
我可以使用PHP从服务器向订阅用户发送浏览器通知吗?我今天看到了这个教程,但这只能从客户端开始.我知道有像pushcrew这样的服务,但我想用PHP和JavaScript开发自己的服务.
我的实际要求是要求用户确认是否可以使用此代码向他们发送通知,
if (Notification.permission !== "granted")
{
Notification.requestPermission();
}
Run Code Online (Sandbox Code Playgroud)
然后在我的网站上发布新文章时显示通知.
注意:浏览器支持无关紧要.
您必须在客户端触发这些通知,因此您需要将它们从PHP服务器提供给您的JavaScript:
即使用户没有打开网站并且最近的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)
| 归档时间: |
|
| 查看次数: |
7428 次 |
| 最近记录: |