javascriptjqueryserver-sent-events

Close An Event Source (SSE) On Page Reload


I noticed that it took my page longer to refresh after adding one SSE (sometimes up to 30 seconds, a big no-no for me). While the page was trying to reload, I noticed that the SSE onmessage event persisted.

function new_event() {
  if (typeof(EventSource !== undefined)) {
    var ES = new EventSource('../folder/file.php');
    /** This event continues while page tries to refresh  **/
    ES.onmessage = function(ev) {
      var data = ev.data;
      // Data is still outputed in the console while page tries to refresh
      console.log(data);
    }
  }

I tried adding an onunload function to the page inside the new_event() function, but that failed miserably.

var ES = new EventSource('../folder/file.php');
window.onunload = function(){
    ES.close();
}

Why does the Event Source persist while the page tries to reload? Is this a back-end problem since the bulk of the work is done on the back-end? Why didn't the onunload event work? Note that this same problem occurs when I try to navigate away from the page.

Is there a way to close the Event Source connection without lagging the page on page refresh?


Solution

  • I encountered this problem. I noticed that the connection does not terminate when the user navigates or reloads the page. You need to explicitly close the connection in the browser when the user navigates away from the page:

      var sse = new EventSource('http://localhost/events');
    
      window.onbeforeunload = function () {
        sse.close();
      };