opentelemetry-js icon indicating copy to clipboard operation
opentelemetry-js copied to clipboard

OTLP exporters shouldn't use `window` as it won't work in web workers

Open schickling opened this issue 3 years ago • 3 comments

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

image

Additional Details

OpenTelemetry Setup Code

No response

package.json

No response

Relevant log output

No response

schickling avatar Aug 15 '22 17:08 schickling

We should run OTLP exporter tests in worker environments just like we do in packages like sdk-trace-base

legendecas avatar Aug 15 '22 17:08 legendecas

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

MSNev avatar Aug 17 '22 16:08 MSNev

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

SaschaBrechmannVHV avatar Nov 11 '22 13:11 SaschaBrechmannVHV

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.

justin0mcateer avatar Mar 06 '23 16:03 justin0mcateer

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

pichlermarc avatar Apr 23 '24 18:04 pichlermarc