我只是想分享我使用的实际实现。我决定使用一个伟大的SAAS,Pusher,因为在实现Push通知时存在许多具有挑战性的问题,正如我在阅读@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>