fanout / reconnecting-eventsource

A small decorator for the JavaScript EventSource API that automatically reconnects
MIT License
97 stars 19 forks source link

Not available to use in a SharedWorker #76

Open bptarpley opened 5 days ago

bptarpley commented 5 days ago

The way this library gets transpiled/minimized for distribution makes it impossible to use inside of a SharedWorker (https://developer.mozilla.org/en-US/docs/Web/API/SharedWorker). This is because the minified version "exports" the module by assigning it to the window object (just open your .min.js distributable file and search for "window"), and SharedWorkers do not have access to a window object since they're not tied to a specific one.

To reproduce this problem, simply create an example.js file with this line:

importScripts('/path/to/ReconnectingEventSource.min.js')

...and reference the example.js file you created with that line in an HTML page:

<html>
<body>
<script type="application/javascript">
    const worker = new SharedWorker('/path/to/example.js')
</script>
</body>
</html>

If you check inspect tools for workers (i.e. chrome://inspect/#workers), you'll find an error about "window" being undefined in the console.

Using EventSource in a SharedWorker is increasingly the way to go, as it effectively gets around the whole 6 connection per browser problem imposed by http/1.1, assuming you use postMessage from inside the worker to relay messages to all windows/tabs/iframes. I was able to fix the issue by simply replacing all instances of "window" with "self" in the minified file (and in .min.js.map). I'm not greatly familiar with transpilers, but I wonder if there's a way to have logic that checks if "window" is available, and if not assign the module to "self" instead...

harmony7 commented 4 days ago

Hi, thanks for filing this issue report. This makes a lot of sense. We'll be looking into this.