35 lines
789 B
JavaScript
Executable File
35 lines
789 B
JavaScript
Executable File
/*
|
|
VARIABLES
|
|
*/
|
|
// Connect to WebSockets server (SocialNetworkConsumer)
|
|
const myWebSocket = new WebSocket(`${document.body.dataset.scheme === 'http' ? 'ws' : 'wss'}://${ document.body.dataset.host }/ws/example/`);
|
|
|
|
/*
|
|
FUNCTIONS
|
|
*/
|
|
|
|
/**
|
|
* Send data to WebSockets server
|
|
* @param {string} message
|
|
* @param {WebSocket} webSocket
|
|
* @return {void}
|
|
*/
|
|
function sendData(message, webSocket) {
|
|
webSocket.send(JSON.stringify(message));
|
|
}
|
|
|
|
/*
|
|
EVENTS
|
|
*/
|
|
|
|
// Event when a new message is received by WebSockets
|
|
myWebSocket.addEventListener("message", (event) => {
|
|
// Parse the data received
|
|
const data = JSON.parse(event.data);
|
|
// Renders the HTML received from the Consumer
|
|
document.querySelector(data.selector).innerHTML = data.html;
|
|
});
|
|
|
|
/*
|
|
INITIALIZATION
|
|
*/ |