-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathwebsocket.html
83 lines (73 loc) · 1.97 KB
/
websocket.html
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>实时聊天</title>
<link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.css">
<link rel="stylesheet" href="websocket.css" />
</head>
<script>
var name = prompt('请输入您的名字');
var message;
function C(selector){
return document.querySelector(selector);
}
if(window.WebSocket){
var url = 'ws://localhost:3000';
var ws = new WebSocket(url);
ws.onopen = function(e){
C('#title').innerText = '连接成功';
}
ws.onerror = function(){
C('#title').innerText = '连接失败';
}
ws.onmessage = function(e){
var li = document.createElement('li');
li.innerText = e.data;
C('#list').appendChild(li);
if(!'Notification' in window ){
alert('不支持通知')
}else if(Notification.permission === 'granted'){
message == e.data?'':notice(e.data)
}else if(Notification.permission !== 'denied'){
Notification.requestPermission(function(permission){
if(permission === 'granted'){
message == e.data?'':notice(e.data)
}
})
}
}
ws.onclose = function(){
C('#title').innerText = '连接关闭';
}
function sendMsg(){
message = name +': '+ document.querySelector('#msg').value;
ws.send(name +': '+ document.querySelector('#msg').value);
}
function notice(msg){
var notification = new Notification('聊天室消息',{
body:msg,
icon:'blank_page_03.png'
})
notification.onclick = function(){
notification.close();
}
}
}else{
C('#title').innerText = '浏览器不支持';
}
</script>
<body>
<div class="container">
<div class="alert alert-success" role="alert" id="title"></div>
<ul id="list">
</ul>
<div>
<textarea class="form-control" id="msg" rows="3"></textarea>
<div class="content">
<button onclick="sendMsg()" type="button" class="btn btn-primary btn-block">发送</button>
</div>
</div>
</div>
</body>
</html>