簡體   English   中英

使用PHP從服務器端進行瀏覽器通知

[英]Browser notifications from server side using PHP

我可以使用PHP從服務器向訂閱的用戶發送瀏覽器通知嗎? 我今天看過本教程 ,但是只能在客戶端使用。 我知道有類似pushcrew的服務,但我想使用PHP和JavaScript開發自己的服務。

我的實際要求是要求用戶確認是否可以使用此代碼向他們發送通知,

if (Notification.permission !== "granted")
{
   Notification.requestPermission();
}

然后在我在網站上發布新文章時顯示通知。

注意:瀏覽器支持無關緊要。

您必須在客戶端觸發這些通知,因此您需要將它們從PHP服務器發送到JavaScript:

  • 每隔x秒執行一次ajax輪詢,例如使用jQuery ajax函數 ,並在服務器返回一個消息時顯示一條消息
  • 通過WebSocket推送消息,例如使用Ratchet

Web Push允許您即使用戶沒有打開網站並且受最新的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"
}

“ test.json”中的JSON服務器答案不顯示消息:

{
    "notify": false
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM