Skip to content

Instantly share code, notes, and snippets.

@rlemon
Created August 16, 2018 15:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rlemon/a97ff8f6bada4df0feb24334f1dba25f to your computer and use it in GitHub Desktop.
Save rlemon/a97ff8f6bada4df0feb24334f1dba25f to your computer and use it in GitHub Desktop.
const headers = {
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
};
fetch('/ws-auth', {
credentials: 'same-origin',
method: 'POST',
headers,
body: `fkey=${fkey().fkey}&roomid=17`
}).then(res => res.json()).then(connect);
function connect({url}) {
const ws = new WebSocket(url + '?l=' + Date.now());
ws.onmessage = onmessage;
ws.onclose = onclose;
}
function onmessage(messageFrame) {
const frame = JSON.parse(messageFrame.data);
for( const room of Object.values(frame) ) {
if( 'e' in room ) {
room.e.forEach(event => {
if( event.event_type === 1 ) {
const { user_name, content, room_name } = event;
console.log(`${user_name} from ${room_name} said: ${content}`);
}
})
}
}
}
function onclose() {
// handle however you want
}
function sendMessage(message, room) {
fetch(`/chats/${room}/messages/new`, {
credentials: 'same-origin',
method: 'POST',
headers,
body: `fkey=${fkey().fkey}&text=${encodeURIComponent(message)}`
}).catch(error => console.error(error));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment