main.js 1.6 KB

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