You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

67 lines
2.2 KiB

11 months ago
  1. <!doctype html>
  2. <html>
  3. <head>
  4. <script type="text/javascript">
  5. window.buttonEl;
  6. window.outputEl;
  7. function handleListen() {
  8. const socket = new WebSocket("ws://localhost:3000/ws");
  9. window.buttonEl.setAttribute("hidden", "true");
  10. socket.addEventListener("message", (event) => {
  11. try {
  12. const data = JSON.parse(event.data);
  13. if (!data.hasOwnProperty("type")) {
  14. window.outputEl.innerHTML += `<p>${data.from} says to ${data.to}: ${data.content}<p></br></br>`;
  15. return;
  16. }
  17. // Handle async input loops
  18. if (data?.type === "WAITING_ON_INPUT") {
  19. // Put in time as hack to now have the prompt block DOM update.
  20. setTimeout(() => {
  21. console.log(
  22. "We are waiting for feedback from the socket. Will timeout in 30s..."
  23. );
  24. const feedback = window.prompt(
  25. "We are waiting for feedback from the socket. Will timeout in 30s..."
  26. );
  27. !!feedback
  28. ? socket.send(
  29. JSON.stringify({ type: "awaitingFeedback", feedback })
  30. )
  31. : socket.send(
  32. JSON.stringify({
  33. type: "awaitingFeedback",
  34. feedback: "exit",
  35. })
  36. );
  37. return;
  38. }, 800);
  39. }
  40. } catch (e) {
  41. console.error("Failed to parse data");
  42. }
  43. });
  44. socket.addEventListener("close", (event) => {
  45. window.outputEl.innerHTML = `<p>Socket connection closed. Test is complete.<p></br></br>`;
  46. window.buttonEl.removeAttribute("hidden");
  47. });
  48. }
  49. window.addEventListener("load", function () {
  50. window.buttonEl = document.getElementById("listen");
  51. window.outputEl = document.getElementById("output");
  52. window.buttonEl.addEventListener("click", handleListen);
  53. });
  54. </script>
  55. </head>
  56. <body>
  57. <button type="button" id="listen">Open websocket connection chat</button>
  58. <div id="output"></div>
  59. </body>
  60. </html>