39 lines
851 B
JavaScript
39 lines
851 B
JavaScript
const isChat = () => {
|
|
return getChat() !== null
|
|
}
|
|
|
|
const getChat = () => {
|
|
return document.querySelector('#chat')
|
|
}
|
|
|
|
const createWebSocketConnection = () => {
|
|
const protocol = location.protocol === 'https:' ? 'wss' : 'ws'
|
|
|
|
return new WebSocket(`${protocol}://${window.location.hostname}:${window.location.port}/ws/chat/messages`)
|
|
}
|
|
|
|
|
|
const runChat = () => {
|
|
const ws = createWebSocketConnection()
|
|
|
|
ws.addEventListener('close', runChat)
|
|
|
|
ws.addEventListener('message', (event) => {
|
|
const items = JSON.parse(event.data)
|
|
|
|
if (items == null || !items.length) {
|
|
return
|
|
}
|
|
|
|
const container = getChat().querySelector('.messages')
|
|
|
|
items.forEach((item) => {
|
|
const message = document.createElement('div')
|
|
message.innerHTML = item
|
|
|
|
container.appendChild(message)
|
|
})
|
|
})
|
|
}
|
|
|
|
export {isChat, runChat}
|