1Password / sys-locale

A small and lightweight Rust library to obtain the active locale on the system.
Apache License 2.0
83 stars 15 forks source link

Add support for workers in WASM #4

Closed oliverdunk closed 2 years ago

oliverdunk commented 2 years ago

Overview

We were panicking when trying to access the locale in a worker. This is because unfortunately, window isn't defined, so Navigator has to be accessed using self instead. This PR implements that to make sure we can reliably use sys-locale in both normal workers as well as service workers.

Additional thoughts

Ideally I'd like to see this sort of thing solved at a lower level, but in general the ecosystem seems to be somewhat immature in its support for anything other than page contexts. As an example - calling web_sys::window() (which returns an option, indicating it will gracefully handle failure) panics in a worker. This makes it hard to gracefully handle and is why my approach here was to implement some new bindings with wasm-bindgen.

I plan to see what we can do to contribute more upstream in the future but I wanted to fix this here to begin with.

How to test

  1. Clone https://github.com/oliverdunk/wasm-worker
  2. Checkout the sys-locale branch
  3. Run make
  4. Open the server URL printed to the console

In the console, you should see the current locale printed from within a worker.

kjvalencik commented 2 years ago

Looks great! I like the consistent and clear panic. I think that will make it easier to discover for users in non-browser runtimes.