Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Not available within web worker context #8

Closed
nickpeihl opened this issue Nov 2, 2017 · 4 comments
Closed

Not available within web worker context #8

nickpeihl opened this issue Nov 2, 2017 · 4 comments

Comments

@nickpeihl
Copy link

I have an idea of using hyperdb and random-access-idb in a web worker context with webworkify, but I am getting an error message in the browser that says "Cannot find module 'crypto'".

I've narrowed it down to the randombytes module in sodium-javascript. The window global is not available in a web worker context so the crypto variable is set to null in this line. This block determines which crypto.getRandomValues function to use. However, it does not have any checks for a web worker context. Most evergreen browsers support the crypto functions in web workers (Edge is an exception).

I'm still unsure the best way to achieve this, but I will play with a few things and submit a PR if I find something suitable. I appreciate any input.

Here's a gist showing the code I'm using. I run it with budo index.js. The browser console should show the error. https://gist.github.com/nickpeihl/0996c84667fc0defc76642ae0af4518a

@emilbayes
Copy link
Member

emilbayes commented Nov 3, 2017

I'm thinking of simply changing this line:

var crypto = typeof window !== 'undefined' ? (window.crypto || window.msCrypto) : null

to:

var crypto = typeof window !== 'undefined' ? (window.crypto || self.crypto || window.msCrypto) : null

Thanks for the detailed bug report!

@emilbayes
Copy link
Member

emilbayes commented Nov 3, 2017

Ah so the trick is to change the line to:

var crypto = typeof global !== 'undefined' ? crypto = (global.crypto || global.msCrypto) : null

and browserify will handle picking either self or window

I will make an update and release a patch. If you want street creds you can make a PR for a test case, eg with your project sending some random bytes back from the webworker ^^

@emilbayes
Copy link
Member

Fixed in 0.5.2 :)

@nickpeihl
Copy link
Author

😍 thanks so much!

ctavan added a commit to uuidjs/uuid that referenced this issue Mar 2, 2020
Edge does not appear to make a global `crypto` variable available in
WebWorkers however the WebCrypto seems to be exposed on the `self`
variable, see sodium-friends/sodium-javascript#8

Since window.self also points to the window object in browsers checking
self should work both, in the browser as well as in WebWorkers.

Fixes #392
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants