main.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. window.onload = function() {
  2. const config = {
  3. "tag": "config",
  4. "game": "testing",
  5. "user": "test_user",
  6. };
  7. const rawHash = window.location.hash;
  8. if (rawHash) {
  9. const hash = rawHash.substr(1, rawHash.length).split(",");
  10. for (let i in hash) {
  11. let elements = hash[i].split(":");
  12. if (elements.length != 2) {
  13. continue;
  14. }
  15. config[elements[0]] = elements[1];
  16. }
  17. }
  18. $("#loggedin").text(`logged in as "${config.user}"`);
  19. $("#gamename").text(`playing in "${config.game}"`);
  20. var loc = window.location, new_uri;
  21. if (loc.protocol === "https:") {
  22. new_uri = "wss:";
  23. } else {
  24. new_uri = "ws:";
  25. }
  26. new_uri += "//" + loc.host;
  27. new_uri += loc.pathname + "socket";
  28. const socket = new WebSocket(new_uri);
  29. socket.addEventListener("open", function (event) {
  30. console.log("Connected to server!");
  31. socket.send(JSON.stringify(config));
  32. });
  33. socket.addEventListener("message", function (event) {
  34. msg = JSON.parse(event.data);
  35. var chat = $(".messages");
  36. chat.append(`<div class="msg"><span class="author">${msg.author}:</span> ${msg.content}</div>`);
  37. chat.animate({scrollTop: chat.prop('scrollHeight')});
  38. });
  39. $('#chatbox').on('keypress', function (e) {
  40. if (e.which === 13) {
  41. $(this).attr("disabled", "disabled");
  42. socket.send(JSON.stringify({
  43. "tag": "post",
  44. "author": config.user,
  45. "content": $('#chatbox').val()
  46. }))
  47. $('#chatbox').val('');
  48. $(this).removeAttr("disabled");
  49. }
  50. });
  51. };