-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathchat.js
47 lines (43 loc) · 1.31 KB
/
chat.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
var user;
var recipient;
$(document).ready(() => {
// sessionStorage.setItem("recipient", "[email protected]");
window.WebSocket = window.WebSocket || window.MozWebSocket;
var ws = new WebSocket('ws://' + window.location.host);
//connection init
ws.onopen = function () {
axios.post("/users/profile", {}).then((response) => {
user = response.data.user;
if (user) {
ws.send(JSON.stringify({ header: "init", body: user }));
}
});
axios.post("/users/get_user", {
user_email: sessionStorage.getItem("recipient")
}).then((response) => {
recipient = response.data.user;
});
$("#chat_box_input").on('keyup', function (e) {
if (e.key === 'Enter' || e.keyCode === 13) {
var text = $("#chat_box_input").val();
$("#chat_box_input").val(""); // Clear input box
ws.send(JSON.stringify({
header: "userMsg", body:
{
body: text, date: new Date(),
language: user.preferred_language,
sender: user,
recipient: recipient
}
}));
}
});
ws.onmessage = function (message) {
console.log(message.data);
var msg=JSON.parse(message.data);
if (msg.header =="userMsg"){
alert("new message\n"+msg.body.body);
}
};
};
});