I am making a chatting application using spring boot 3 and i use web socket to make connection. I’ve created a web page with 2 buttons “Start Chat” and “Close Chat”. When i click the “Start Chat” button it adds html codes into an html element(id=”chat”). This html code is from “https://spring.io/guides/gs/messaging-stomp-websocket”. And when i click the “Close Chat” button it removes the html codes from the element. My issue:
When i click the Start Chat button and Connect it works well. After closing, if i open the chat again and click Connect the page is reloaded. I don’t want this reloading when i try to connect chat again.
(Note: After clearing the chat elements from page i also call disconnect() function from webSocket.js )
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@stomp/[email protected]/bundles/stomp.umd.min.js"></script>
<link rel="stylesheet" href="/css/bootstrap.min.css">
<script src="/js/bootstrap.bundle.min.js"></script>
<script src="/js/app.js"></script>
</head>
<body>
<div th:insert="components/header :: header"></div>
<div class="container-fluid">
<div class="col-md-3">
<div class="row">
<button onclick="openChat()" class="btn btn-primary m-3">Start Chatting</button>
<button onclick="closeChat()" class="btn btn-primary m-3">Close Chat</button>
</div>
</div>
<div class="col-md-9">
<div class="row m-3" id="chat"></div>
</div>
</div>
<script>
function closeChat() {
const chatElement = document.getElementById("main-content");
chatElement.remove();
disconnect();
const scriptElement = document.getElementById("webSocketJs");
if (scriptElement) {
scriptElement.remove();
}
}
function openChat() {
event.preventDefault();
const chatElement = document.getElementById("chat");
const content =
`<div id="main-content" className="container">
<div className="row">
<div className="col-md-6">
<form className="form-inline">
<div className="form-group">
<label htmlFor="connect">WebSocket connection:</label>
<button id="connect" className="btn btn-default" type="submit" >Connect</button>
<button id="disconnect" className="btn btn-default" type="submit"
disabled="disabled">Disconnect
</button>
</div>
</form>
</div>
<div className="col-md-6">
<form className="form-inline">
<div className="form-group">
<label htmlFor="name">What is your name?</label>
<input type="text" id="name" className="form-control" placeholder="Your name here..."/>
</div>
<button id="send" className="btn btn-default" type="submit">Send</button>
</form>
</div>
</div>
<div className="row">
<div className="col-md-12">
<table id="conversation" className="table table-striped">
<thead>
<tr>
<th>Greetings</th>
</tr>
</thead>
<tbody id="greetings">
</tbody>
</table>
</div>
</div>
</div>`;
chatElement.innerHTML = content;
const scriptElement = document.getElementById("webSocketJs");
if (!scriptElement) {
let webSocketScript = document.createElement('script');
webSocketScript.setAttribute('src', '/js/webSocket.js');
webSocketScript.setAttribute('id', 'webSocketJs');
document.body.appendChild(webSocketScript);
}
}
</script>
</body>
</html>
const stompClient = new StompJs.Client({
brokerURL: 'ws://localhost:8080/gs-guide-websocket'
});
stompClient.onConnect = (frame) => {
setConnected(true);
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/greetings', (greeting) => {
showGreeting(JSON.parse(greeting.body).content);
});
};
stompClient.onWebSocketError = (error) => {
console.error('Error with websocket', error);
};
stompClient.onStompError = (frame) => {
console.error('Broker reported error: ' + frame.headers['message']);
console.error('Additional details: ' + frame.body);
};
function setConnected(connected) {
$("#connect").prop("disabled", connected);
$("#disconnect").prop("disabled", !connected);
if (connected) {
$("#conversation").show();
}
else {
$("#conversation").hide();
}
$("#greetings").html("");
}
function connect() {
stompClient.activate();
}
function disconnect() {
stompClient.deactivate();
setConnected(false);
console.log("Disconnected");
}
function sendName() {
stompClient.publish({
destination: "/app/hello",
body: JSON.stringify({'name': $("#name").val()})
});
}
function showGreeting(message) {
$("#greetings").append("<tr><td>" + message + "</td></tr>");
}
$(function () {
$("form").on('submit', (e) => e.preventDefault());
$( "#connect" ).click(() => connect());
$( "#disconnect" ).click(() => disconnect());
$( "#send" ).click(() => sendName());
});
First one is my html page, and second one is webSocket.js file.