Untitled

mail@pastecode.io avatar
unknown
html
a year ago
2.3 kB
1
Indexable
Never
<!DOCTYPE html>
<html>

<head>
    <title>Chat</title>
    <style>
        input {
            display: block;
        }

        ul {
            list-style: none;
        }
    </style>
</head>

<body>
    <h2>Welcome, <span id="username"></span>!</h2>
    <ul id="messages"></ul>
    <form id="chatbox">
        <textarea></textarea>
        <input type="submit" value="Send" />
    </form>

    <form id="nameForm" name="nameForm" action="/register" method="POST">
        <input type="text" id="nameInput" name="name" placeholder="Name"/>
        <input type="submit" value="Submit your name!" />
    </form>

    <script>
        var socket = null;
        var msgBox = document.querySelector("#chatbox textarea");
        var messages = document.getElementById("messages");
        var username = document.getElementById("username");

        const now = new Date();
        const hours = now.getHours();
        const minutes = now.getMinutes();


        document.getElementById("chatbox").onsubmit = function () {
            if (!msgBox.value) return false;
            if (!socket) {
                alert("Error: There is no socket connection.");
                return false;
            }

            socket.send(msgBox.value);
            msgBox.value = "";
            return false;
        };

        if (!window["WebSocket"]) {
            alert("Error: Your browser does not support web sockets.")
        } else {
            socket = new WebSocket("ws://" + window.location.host + "/room");
            socket.onclose = function () {
                alert("Connection has been closed.");
            };
            socket.onmessage = function (e) {
                var username = document.getElementById("username");
                if (e.data.startsWith("You are connected as: ")) {
                username.textContent = e.data.substring("You are connected as: ".length);
                } else {
                var message = document.createElement("li");
                var data = JSON.parse(e.data);
                message.textContent = data.name + ": " + data.message + " " + hours + ":" + minutes;
                messages.appendChild(message);
            };
        }
        }
    </script>
</body>

</html>