The example below is based on a small javascript library that will make it easier for you to create your own web applications with websocket communication.
/** * WebSocket.CZ - Web Notifications * Basic javascript application for real time web notification */ window.simpleWebNtf = new SimpleDataAPP({ appName: "webntf" , svcName: "svc/webntf" , wssGateway: "apps.dataapps.cz/ws/gtw/" , docCookie: new SimpleDocCookie() /* THE IDENTIFIER OF YOUR WEBSOCKET SERVER (contact service provider) */ , wssKey: ".........." /** * Event handler that is fired when a websocket connection is opened */ , onOpen: function(evn){ this.initSvc({ target:this.svcName , token:this.getToken() }); this.wsPing(); } /** * Event handler that fires when a message is received from websocket */ , onData: function(msg){ if ( msg.header.type != undefined && msg.header.type == "message" ) { /* WRITE HERE YOUR CODE FOR DISPLAY NOTIFICATION (see example) */ console.log(msg.body.data); } } /** * Event handler that is fired when the application is initialized */ , onInit: function(app){ this.setToken(function(){ return(app.docCookie.get("WSGSESSID")); }); this.wsOpen(this.wssGateway + this.wssKey + "/"); } }); /** * Initialize a simple application */ window.simpleWebNtf.init();
A snippet of javascript code (application event handler, see example above) that captures and processes a websocket messages and displays notifications on a web page or through a browser Notification API.
... , onData: function(msg){ // check websocket message type if (msg.header.type != undefined && msg.header.type == "message") { // get data of notification var data = msg.body.data; // check if title of notification exists if (data.title != undefined && data.title.length > 0) { // check granted permission if (Notification.permission === "granted") { // display notification via browser var notification = new Notification(data.title, data); // or display notification in the web page } else { /* ... your own code ... */ } } } } ...
For easy development, use and customize the basic javascript application for real-time web notifications via websocket. Download a free ZIP package with javascript application for web notifications.