-
Notifications
You must be signed in to change notification settings - Fork 4
/
websocket-component.html
249 lines (224 loc) · 5.9 KB
/
websocket-component.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
<!--
Copyright (c) 2018 Willem Burgers. All rights reserved.
This code may only be used under the BSD style license found at http://wburgers.github.io/LICENSE.txt
For a list of Contributors check https://github.com/wburgers/websocket-component/graphs/contributors
-->
<link rel="import" href="../polymer/polymer.html">
<!--
A Polymer wrapper for a websocket connection.
Example:
<websocket-component auto handle-visibility url="wss://echo.websocket.org"></websocket-component>
@element websocket-component
@demo demo/index.html
-->
<dom-module id="websocket-component">
<template>
<style>
:host {
display: none;
}
</style>
</template>
<script>
/**
* @mixinFunction
* @polymer
*/
const WebsocketComponentBehavior = subclass =>class extends subclass {
static get properties() {
return {
/**
* The url to connect to
*/
url: {
type: String,
value: "", observer: '_urlChange'
},
/**
* An array of subprotocols for the websocket
*/
protocols: {
type: Array,
value: () => []
},
/**
* This status represents the websocket status. Any other element can bind to this status to get updates.
* @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket#Ready_state_constants
*/
status: {
type: Number,
readOnly: true,
notify: true,
value: -1
},
/**
* If this boolean is set, the websocket will automatically connect when the url is specified
*/
auto: {
type: Boolean,
value: false,
observer: '_autoChange'
},
/**
* If this boolean is set, the websocket will automatically close and reopen when the tab/page is out of focus and focussed again respectively
*/
handleVisibility: {
type: Boolean,
value: false,
},
_ws: {
type: Object,
observer: '_wsChange'
},
/**
* If this boolean is set, a send-request will be queued, if it failed because of the
* websocket not beeing ready. Once the websocket transits into the OPEN state, it sends them one by one
*/
queueIfFailed: {
type: Boolean,
value: false
},
_sendQueue: {
type: Array,
value: () => []
}
}
}
static get observers() {
return [
'_computeStatus(_ws.readyState)'
]
}
constructor() {
super();
}
ready() {
super.ready();
if (this.handleVisibility && typeof document.hidden !== 'undefined') {
document.addEventListener('visibilitychange', this._handleVisibilityChange.bind(this), false);
}
}
/**
* Open the connection manually. May throw errors when already connected or no url is specified.
*/
open() {
if (!this || !this.url || this.url === "") {
throw new Error("websocket-component(open): no url specified.");
}
if (this._ws) {
throw new Error("websocket-component(open): already connected");
}
this._ws = new WebSocket(this.url, this.protocols);
this._addEvents();
}
/**
* Send data over the websocket. Throws an error when the websocket is not connected and sendIfFailed is not set.
*/
send(data) {
if (!this._ws || this.status !== 1) {
if(!this.queueIfFailed) {
throw new Error("websocket-component(send): not connected.");
}
this.push('_sendQueue', data);
} else {
try {
this._ws.send(data);
} catch(error) {
if(this.queueIfFailed) {
this.push('_sendQueue', data);
} else {
throw new Error("websocket-component(send): failed.", error);
}
}
}
}
/**
* Close the connection manually. Trows an error when the websocket is not connected.
*/
close() {
if (!this || !this._ws) {
throw new Error("websocket-component(close): not connected.");
}
this._ws.close();
this._ws = null;
}
/**
* Try to send the send-queue
*/
_processSendQueue() {
//we use this iteration method to prevent an infinite loop if send, failes and queue isn't processed
const queueLen = this._sendQueue.length;
for(let i = queueLen; i > 0; i--) {
this.send(this.pop('_sendQueue'));
}
}
_onwsopen() {
this._computeStatus(undefined);
this.dispatchEvent(new CustomEvent("websocket-open"));
this._processSendQueue();
}
_onwserror(error) {
this._setStatus(-1);
this.dispatchEvent(new CustomEvent("websocket-error", {detail: {data: error.data}}));
}
_onwsmessage(event) {
this.dispatchEvent(new CustomEvent("websocket-message", {detail: {data: event.data}}));
}
_onwsclose(event) {
this._setStatus(-1);
this.dispatchEvent(new CustomEvent("websocket-close", {detail: {code: event.code, reason: event.reason}}));
}
_computeStatus(readyState) {
if (this._ws) {
this._setStatus(this._ws.readyState);
} else {
this._setStatus(-1);
}
}
_urlChange() {
if (this.auto && this.url.length > 0) {
if (this._ws) {
this.close();
}
this.open();
}
}
_autoChange() {
if (!this._ws && this.auto && this.url.length > 0) {
this.open();
}
}
_wsChange() {
if (!this._ws) {
this._computeStatus(undefined);
}
}
_handleVisibilityChange() {
if (document.hidden) {
this.close();
} else {
this.open();
}
}
_addEvent(name, callback) {
this._ws.addEventListener(name, callback.bind(this));
}
_addEvents() {
this._addEvent("open", this._onwsopen);
this._addEvent("error", this._onwserror);
this._addEvent("message", this._onwsmessage);
this._addEvent("close", this._onwsclose);
}
};
/**
* @extends {Polymer.Element}
* @appliesMixin WebsocketComponentBehavior
*/
class WebsocketComponent extends WebsocketComponentBehavior(Polymer.Element) {
static get is() {
return "websocket-component";
}
}
window.customElements.define(WebsocketComponent.is, WebsocketComponent);
</script>
</dom-module>