wsrecon
Version:
Isomorphic auto reconnecting web socket client with callback support
1 lines • 636 B
JavaScript
window.wsrecon=function(e,n){n||(n={}),void 0===n.timeout&&(n.timeout=1);for(var o,t={},r=["message","open","close","error"],i=0;i<r.length;i++)t[r[i]]=[];function s(e,...n){for(var o=0;o<t[e].length;o++)t[e][o](...n)}function c(t,r){(o=new WebSocket(e)).onmessage=function(e){s("message",JSON.parse(e.data),e)},o.onopen=function(e){t&&t(u),s("open",u,e)},o.onerror=function(e){r&&r(e),s("error",e)},o.onclose=function(e){n.timeout&&setTimeout(c,n.timeout),s("close",e)}}var u={on:function(e,n){t[e].push(n)},open:c,send:function(e){1==o.readyState&&o.send(JSON.stringify(e))},close:function(e){o.close(e||1e3)}};return new Promise(c)};