forked from byjg/jquery-sse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.sse.min.js
1 lines (1 loc) · 2.52 KB
/
jquery.sse.min.js
1
!function($){function e(e){e.type="event",e.instance=new EventSource(e._url),e.instance.successCount=0,e.instance.onmessage=e._settings.onMessage,e.instance.onopen=function(n){0===e.instance.successCount++&&e._settings.onOpen(n)},e.instance.onerror=function(n){n.target.readyState===EventSource.CLOSED&&e._settings.onError(n)};for(var n in e._settings.events)e.instance.addEventListener(n,e._settings.events[n],!1)}function n(e){e.type="ajax",e.instance={successCount:0,id:null,retry:3e3,data:"",event:""},i(e)}function t(e,n){if(e.instance){0===e.instance.successCount++&&e._settings.onOpen();var t=n.split("\n");e.instance.data="";var s=0;for(var i in t){var a=t[i].indexOf(":"),r=[t[i].substr(0,a),t[i].substr(a+1)];switch(r[0]){case"":r[1]||1!==s++||(eventMessage={data:e.instance.data,lastEventId:e.instance.id,origin:"http://"+e._remoteHost,returnValue:!0},e.instance.event&&e._settings.events[e.instance.event]?e._settings.events[e.instance.event](eventMessage):e._settings.onMessage(eventMessage),e.instance.data="",e.instance.event="",s=0);break;case"retry":s=0,e.instance.retry=parseInt(r[1].trim());break;case"id":s=0,e.instance.id=r[1].trim();break;case"event":s=0,e.instance.event=r[1].trim();break;case"data":s=0,e.instance.data+=(""!==e.instance.data?"\n":"")+r[1].trim();break;default:s=0}}}}function s(e){$.ajax({type:"HEAD",headers:e._settings.headers,url:e._url,complete:function(n){e._remoteHost=n.getResponseHeader("Host")}})}function i(e){if(e.instance){e._remoteHost||s(e);var n={"Last-Event-ID":e.instance.id};$.extend(n,e._settings.headers);var a=!1,r="";$.ajax({url:e._url,method:"GET",headers:n,xhrFields:{onprogress:function(n){var s=n.currentTarget.response;r+=a===!1?s:s.substring(a),a=s.length;var i=r.lastIndexOf("\n\n");if(i>=0){var o=r.substring(0,i+2);r=r.substring(i+2),t(e,o)}}},success:function(){setTimeout(function(){i(e)},e.instance.retry)},error:e._settings.onError})}}$.extend({SSE:function(t,s){var i={instance:null,type:null},a={onOpen:function(e){},onEnd:function(e){},onError:function(e){},onMessage:function(e){},options:{},headers:{},events:{}};return $.extend(a,s),i._url=t,i._remoteHost=null,i._settings=a,i._start=i.start,i.start=function(){return!this.instance&&(!window.EventSource||this._settings.options.forceAjax||Object.keys(this._settings.headers).length>0?n(this):e(this),!0)},i.stop=function(){return!!this.instance&&(!window.EventSource||this._settings.options.forceAjax||Object.keys(this._settings.headers).length>0||this.instance.close(),this._settings.onEnd(),this.instance=null,this.type=null,!0)},i}})}(jQuery);