gomoku/public/scripts/make-ws-connection.js

27 lines
893 B
JavaScript
Executable File

// Get gameId and playerId from meta tags generated by the server
const gameIdMeta = document.querySelector('meta[name="gameId"]');
const playerIdMeta = document.querySelector('meta[name="playerId"]');
if (!gameIdMeta || !playerIdMeta) {
console.error('Game ID or Player ID meta tags not found.');
}
const gameId = gameIdMeta.content;
const playerId = playerIdMeta.content;
// Dynamically construct WebSocket URL
let wsProtocol;
if (window.location.protocol === 'https:') {
wsProtocol = 'wss';
} else {
wsProtocol = 'ws';
}
const wsUrl = `${wsProtocol}://${window.location.host}/ws?gameId=${gameId}&playerId=${playerId}`;
// Get the game container element
const gameContainer = document.getElementById('ws-container');
// Set the ws-connect attribute
gameContainer.setAttribute('ws-connect', wsUrl);
// Tell HTMX to connect the WebSocket
htmx.trigger(gameContainer, ' and connect');