我只是想分享我使用的实际实现。我决定使用一个很棒的 SAAS,Pusher,因为在实现推送通知方面存在许多具有挑战性的问题,正如我在阅读 @Virendra 的优秀答案中的链接时意识到的那样,Pusher 可以为您解决。
最让我印象深刻的是您只需编写很少的代码即可完成这项工作。见下文。我的服务器端是 PHP(Pusher 有多种语言的库)。
require('/application/thirdParty/pusher-html5-realtime-push-notifications/lib/squeeks-Pusher-PHP/lib/Pusher.php');
require('/application/thirdParty/pusher-html5-realtime-push-notifications/config.php');
$pusher = new Pusher(APP_KEY, APP_SECRET, APP_ID);
foreach($recipients as $row){
$channel='my-channel'.$row->recipient_id;
$pusher->trigger($channel, 'notifications',
array('message' => $row->message,
'notification_id' => $row->notification_id)
);
}
这是 HTML/JS(不要不知所措,这些代码的大部分只是为了填充小圆圈和列表以及 Stackoverflow 和其他人所做的传入通知):
<script src="/application/thirdParty/pusher.min.js"></script>
<script>
var myID=179; // would receive notification if myID matches $row->recipient_id above;
var myChannel = pusher.subscribe('my-channel'+myID);
myChannel.bind('notifications',
function(data) {
var message=String(data.message),
url='/notifications/'+data.notification_id,
icon='<i class=\'icon-heart\'></i>',
urlText=icon+message;
var notificationRow='<li><a href='+url+'>'+urlText+'</a></li>';
$('#notificationsDropdownList').prepend(notificationRow);
if(notificationCircleCount==0){
notificationCircleCount++;
$notificationCircle.show();
$notificationCircleCount.html(notificationCircleCount);
}
else{
notificationCircleCount++;
$notificationCircleCount.html(notificationCircleCount);
}
console.log('Pusher happened'+data.message);
} //function
); //myChannel
</script>