opentelemetry-js
opentelemetry-js copied to clipboard
OTLP exporters shouldn't use `window` as it won't work in web workers
What happened?
Steps to Reproduce
Try to use @opentelemetry/exporter-trace-otlp-http in a web worker.
Expected Result
Otel should work in a web worker
Actual Result
An error is thrown with window is not defined

Additional Details
OpenTelemetry Setup Code
No response
package.json
No response
Relevant log output
No response
We should run OTLP exporter tests in worker environments just like we do in packages like sdk-trace-base
Looking at the code for how the exporter base "uses" the window to listen for the unload event (it should be listening for more and it probably should not be just shutting down as there may be additional events (spans) that are created as part of shutdown that still need to be sent).
Having said that though, as mentioned in the SIG, because of the way this is currently coded this would be a feature request change and at the very least the "base" should be changed to "check" for the existence of window and the add/remove EventListener
There is a JS lib, to move JS at the Browser to WebWorker. partytown
Partytown is a lazy-loaded library to help relocate resource intensive scripts into a web worker, and off of the main thread. Its goal is to help speed up sites by dedicating the main thread to your code, and offloading third-party scripts to a web worker.
This could a way around. Regards, Sascha
I was able to get this working in WebWorkers by simply changing the two instances of 'window' in OTLPExporterBrowserBase to 'globalThis'.
I haven't tested this elsewhere, but this should work in pretty much any environment since early 2019.
This was fixed by #4157 and then the handlers were removed completely in #4438. Please let me know if there's any issues still and I'll re-open