Server sent events and browser limits

后端 未结 3 812
被撕碎了的回忆
被撕碎了的回忆 2021-01-30 08:59

I have a web application that listens for Server Sent Events. While I was working and testing with multiple windows open, things were not working and I banged my head for severa

3条回答
  •  失恋的感觉
    2021-01-30 09:52

    One way to get around this issue is to shut down the connections on all the hidden tabs, and reconnect when the user visits a hidden tab.

    I'm working with an application that uniquely identifies users which allowed me to implement this simple work-around:

    1. When users connect to sse, store their identifier, along with a timestamp of when their tab loaded. If you are not currently identifying users in your app, consider using sessions & cookies.
    2. When a new tab opens and connects to sse, in your server-side code, send a message to all other connections associated with that identifier (that do not have the current timestamp) telling the front-end to close down the EventSource. The front-end handler would look something like this:

      myEventSourceObject.addEventListener('close', () => { myEventSourceObject.close(); myEventSourceObject = null; });

    3. Use the javascript page visibility api to check to see if an old tab is visible again, and re-connect that tab to the sse if it is.

      document.addEventListener('visibilitychange', () => { if (!document.hidden && myEventSourceObject === null) { // reconnect your eventsource here } });

    4. If you set up your server code like step 2 describes, on re-connect, the server-side code will remove all the other connections to the sse. Hence, you can click between your tabs and the EventSource for each tab will only be connected when you are viewing the page.

    Note that the page visibility api isn't available on some legacy browsers: https://caniuse.com/#feat=pagevisibility

提交回复
热议问题