github.com/brandur/modulir@v0.0.0-20240305213423-94ee82929cbd/js/websocket.js (about) 1 function connect() { 2 var url = "ws://localhost:{{.Port}}/websocket"; 3 4 console.log(`Connecting to Modulir: ${url}`); 5 var socket = new WebSocket(url); 6 7 socket.onclose = function(event) { 8 console.log("Websocket connection closed or unable to connect; starting reconnect timeout"); 9 10 // Allow the last socket to be cleaned up. 11 socket = null; 12 13 // Set an interval to continue trying to reconnect periodically until we 14 // succeed. 15 setTimeout(function() { 16 connect(); 17 }, 5000) 18 } 19 20 socket.onmessage = function(event) { 21 console.log(`Received event of type '${event.type}' data: ${event.data}`); 22 23 var data = JSON.parse(event.data); 24 25 switch(data.type) { 26 case "build_complete": 27 // 1000 = "Normal closure" and the second parameter is a human-readable 28 // reason. 29 socket.close(1000, "Reloading page after receiving build_complete"); 30 31 console.log("Reloading page after receiving build_complete"); 32 location.reload(true); 33 34 break; 35 36 default: 37 console.log(`Don't know how to handle type '${data.type}'`); 38 } 39 } 40 41 socket.onopen = function(event) { 42 console.log("Websocket connected"); 43 } 44 } 45 46 connect();