3

デスクトップ通知を送信するには、このコードを使用します。( https://developer.mozilla.org/en/docs/Web/API/notificationから)

<button onclick="notifyMe()">Notify me!</button>

function notifyMe() {
  // Let's check if the browser supports notifications
  if (!("Notification" in window)) {
    alert("This browser does not support desktop notification");
  }

  // Let's check whether notification permissions have already been granted
  else if (Notification.permission === "granted") {
    // If it's okay let's create a notification
    var notification = new Notification("Hi there!");
  }

  // Otherwise, we need to ask the user for permission
  else if (Notification.permission !== 'denied') {
    Notification.requestPermission(function (permission) {
      // If the user accepts, let's create a notification
      if (permission === "granted") {
        var notification = new Notification("Hi there!");
      }
    });
  }

  // At last, if the user has denied notifications, and you 
  // want to be respectful there is no need to bother them any more.
}

これはボタンを押すと同じページで機能しますが、これらの通知を動的に管理したい場合はどうすればよいですか? つまり、バックエンド (管理者) から通知をプッシュすると、フロントエンド (通知を許可するユーザー) にメッセージが表示されます。

4

1 に答える 1

2

次の手順を実行します

  1. ユーザー側に関数 {notifyMe(msg)} があります。
    Javascript では、問題の notifyMe(); のように関数を定義します。
  2. 特定の間隔で ajax 呼び出しを送信して、現在ログインしているユーザーの管理ステータスを確認し
    ます 特定の間隔でサーバーに ajax 呼び出しを送信します。setInterval 関数内で Ajax を呼び出し、20 秒ごとにリクエストを送信します。
  3. 管理ステータスがメッセージまたはフラグで設定されている場合、メッセージを定義済み関数 {notifyMe(msg)} に渡します。ユーザーは自動的に通知されます。
    サーバー側スクリプトで、管理者がユーザー (ユーザー ID 10 など) に対して通知が有効になっているかどうかを確認します。サーバー側で有効 (ユーザー ID 10) に設定されている場合は、ajax リターンで関数notifyMe()を呼び出します。通知を停止することを決定したら、javascript で間隔をクリアします。

セッションから、または Ajax 呼び出しからのパラメーターのいずれかから、サーバー側スクリプトでユーザー ID を取得できます。したがって、ユーザーIDに基づいて、AjaxとnotifyMe()を呼び出すかどうかを実行します

于 2016-09-06T13:57:14.883 に答える