2017-08-12 269 views
0

我正在製作一個Web應用程序,要求用戶從服務器獲取推送通知。我正在考慮使用webSockets來做到這一點。我有一個基本的例子工作。服務器正在運行。我只是想知道是否有更好的實現推送通知的方式?推送通知web應用程序

<html> 
<head></head> 
<body> 
    <script type="text/javascript"> 
     var sock = null; 
     var wsuri = "ws://192.168.0.165:8080"; 

     window.onload = function() { 

      console.log("onload"); 

      sock = new WebSocket(wsuri); 

      sock.onopen = function() { 
       console.log("connected to " + wsuri); 
      } 

      sock.onclose = function(e) { 
       console.log("connection closed (" + e.code + ")"); 
      } 

      sock.onmessage = function(e) { 
       console.log("message received: " + e.data); 
       document.getElementById("p1").innerHTML = e.data; 
      } 
     }; 

     function send() { 
      var msg = document.getElementById('message').value; 
      sock.send(msg); 
     }; 
    </script> 
    <h1>WebSocket Echo Test</h1> 
    <form> 
     <p> 
      Message: <input id="message" type="text" value="Hello, world!"> 
     </p> 

     <p id="p1">MSG!</p> 
    </form> 
    <button onclick="send();">Send Message</button> 
</body> 
</html> 
+0

SSE是一個選項 - 在這裏看到答案https://stackoverflow.com/questions/5195452/websockets -VS-服務器發送的事件 - 的EventSource –

回答

0

有關前端推送通知您可以用火力https://www.npmjs.com/package/firebase:與推送通知 https://peter-gribanov.github.io/serviceworker/

  • Github的樣品 https://github.com/firebase/quickstart-js

  • 添加火力地堡到

    <script src="https://www.gstatic.com/firebasejs/4.2.0/firebase.js"></script> 
     
    <script> 
     
        // Initialize Firebase 
     
        // TODO: Replace with your project's customized code snippet 
     
        var config = { 
     
        apiKey: "<API_KEY>", 
     
        authDomain: "<PROJECT_ID>.firebaseapp.com", 
     
        databaseURL: "https://<DATABASE_NAME>.firebaseio.com", 
     
        storageBucket: "<BUCKET>.appspot.com", 
     
        messagingSenderId: "<SENDER_ID>", 
     
        }; 
     
        firebase.initializeApp(config); 
     
    </script>